<?php
require_once __DIR__ . '/../../../includes/auth.php';
requireLogin();
requirePermission('create_ticket');

require_once __DIR__ . '/../../../config/database.php';

/* =============================
   HANDLE FORM SUBMISSION
============================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $tenant_id  = $_SESSION['tenant_id'] ?? 1;
    $company_id = $_SESSION['company_id'] ?? null;
    $created_by = $_SESSION['user_id'];

    $source = $_POST['source'] ?? 'Email';
    $category = $_POST['category'] ?? 'General';
    $priority = $_POST['priority'] ?? 'Medium';
    $subject = trim($_POST['subject'] ?? '');
    $description = trim($_POST['description'] ?? '');

    if ($subject !== '' && $description !== '') {

        $ticket_number = 'TKT-' . time();

        $assigned_to = !empty($_POST['assigned_to']) ? $_POST['assigned_to'] : null;
        $due_at = !empty($_POST['due_at']) ? $_POST['due_at'] : null;

        /* =============================
           PIP DEFAULTS
        ============================== */
        $pip_stage = null;
        $pip_review_date = null;

        if ($category === 'Performance / PIP') {
            $pip_stage = 'Stage 1 – Verbal Warning';
            $pip_review_date = !empty($_POST['pip_review_date']) 
                ? $_POST['pip_review_date'] 
                : date('Y-m-d', strtotime('+7 days'));
        }

        $stmt = $pdo->prepare("
            INSERT INTO operations_tickets
            (
                tenant_id,
                company_id,
                ticket_number,
                source,
                category,
                priority,
                subject,
                description,
                status,
                assigned_to,
                due_at,
                pip_stage,
                pip_review_date,
                created_by,
                created_at
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Open', ?, ?, ?, ?, ?, NOW())
        ");

        $stmt->execute([
            $tenant_id,
            $company_id,
            $ticket_number,
            $source,
            $category,
            $priority,
            $subject,
            $description,
            $assigned_to,
            $due_at,
            $pip_stage,
            $pip_review_date,
            $created_by
        ]);

        $ticket_id = $pdo->lastInsertId();
        require_once __DIR__ . '/../../../includes/notifications.php';

/* =============================
   CREATE NOTIFICATION
============================= */

$link = "/core/public/operations/tickets/view.php?id=" . $ticket_id;

if (!empty($assigned_to)) {

    createNotification(
        $pdo,
        $company_id,
        $assigned_to,
        'ticket_assigned',
        'New Ticket Assigned',
        $subject,
        $link
    );

}

        /* =============================
           LOG EVENT (TIMELINE)
        ============================== */
        $evt = $pdo->prepare("
            INSERT INTO operations_ticket_events
            (ticket_id, event_type, message, created_by, created_at)
            VALUES (?, 'CREATED', ?, ?, NOW())
        ");

        $message = ($category === 'Performance / PIP')
            ? 'PIP initiated - ' . $pip_stage
            : 'Ticket created';

        $evt->execute([$ticket_id, $message, $created_by]);

if ($assigned_to) {

require_once __DIR__ . '/../../../includes/mailer.php';

// GET USER EMAIL
$u = $pdo->prepare("SELECT email, full_name FROM users WHERE id = ?");
$u->execute([$assigned_to]);
$user = $u->fetch(PDO::FETCH_ASSOC);

if ($user && !empty($user['email'])) {

    $emailBody = "
<div style='font-family:Poppins,Arial,sans-serif;background:#f4f6f8;padding:20px;'>

    <div style='max-width:600px;margin:0 auto;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 6px 20px rgba(0,0,0,0.08);'>

        <div style='background:#f2531e;color:#fff;padding:18px 20px;font-size:18px;font-weight:600;'>
            InfraCore™ Notification
        </div>

        <div style='padding:25px;'>

            <p style='margin:0 0 10px 0;font-size:14px;color:#555;'>
                Hello <strong>{$user['full_name']}</strong>,
            </p>

            <p style='margin:0 0 20px 0;font-size:14px;color:#555;'>
                You have been assigned a new ticket:
            </p>

            <div style='background:#f9fafb;border-left:4px solid #f2531e;padding:15px;border-radius:8px;margin-bottom:20px;'>

                <div style='font-size:16px;font-weight:600;color:#111;'>
                    {$ticket_number}
                </div>

                <div style='font-size:14px;color:#555;margin-top:5px;'>
                    {$subject}
                </div>

            </div>

            <a href='https://crm.edmsolutions.co.za/core/public/operations/tickets/view.php?id={$ticket_id}'
               style='display:inline-block;background:#f2531e;color:#fff;padding:12px 20px;border-radius:8px;text-decoration:none;font-size:14px;font-weight:500;'>
               View Ticket
            </a>

        </div>

        <div style='padding:15px 20px;font-size:12px;color:#888;background:#f9fafb;'>
            © ".date('Y')." InfraCore™ • EDM Solutions<br>
            Secure Infrastructure Operating System
        </div>

    </div>

</div>
";

    sendEmail(
        $user['email'],
        "New Ticket Assigned - {$ticket_number}",
        $emailBody
    );
}

    
    }

        header("Location: index.php");
        exit;
    }
}

/* =============================
   LOAD USERS (TENANT SAFE)
============================= */
$company_id = $_SESSION['company_id'];

$userStmt = $pdo->prepare("
    SELECT id, full_name 
    FROM users 
    WHERE status = 'ACTIVE' 
      AND company_id = ?
    ORDER BY full_name ASC
");
$userStmt->execute([$company_id]);
$users = $userStmt->fetchAll(PDO::FETCH_ASSOC);

/* LOAD MASTER LAYOUT */
require_once __DIR__ . '/../../../includes/layout.php';
?>

<div class="page-header">
    <h2>Create New Ticket</h2>
    <p class="page-subtitle">
        Log a complaint, request, or operational issue
    </p>
</div>

<div class="card-form">
<form method="POST">

<div style="margin-bottom:15px;">
    <label>Source</label>
    <select name="source" required>
        <option>Email</option>
        <option>Phone</option>
        <option>SalesIQ</option>
        <option>Walk-in</option>
        <option>WhatsApp</option>
    </select>
</div>

<div style="margin-bottom:15px;">
    <label>Category</label>
    <select name="category" id="category" required>
        <option>General</option>
        <option>Fault</option>
        <option>Installation</option>
        <option>Replacement</option>
        <option>Billing</option>
        <option>Token Issue</option>
        <option>Performance / PIP</option>
    </select>
</div>

<div id="pip-fields" style="display:none; margin-bottom:15px;">
    <label>PIP Review Date</label>
    <input type="date" name="pip_review_date">
</div>

<div style="margin-bottom:15px;">
    <label>Priority</label>
    <select name="priority" required>
        <option>Low</option>
        <option selected>Medium</option>
        <option>High</option>
        <option>Critical</option>
    </select>
</div>

<div style="margin-bottom:15px;">
    <label>Assign To</label>

    <select name="assigned_to">
        <option value="">-- Unassigned --</option>
        <?php foreach ($users as $u): ?>
            <option value="<?= $u['id'] ?>">
                <?= htmlspecialchars($u['full_name']) ?>
            </option>
        <?php endforeach; ?>
    </select>
</div>

<div style="margin-bottom:15px;">
    <label>Due Date (SLA)</label>
    <input type="datetime-local" name="due_at">
</div>

<div style="margin-bottom:15px;">
    <label>Subject</label>
    <input type="text" name="subject" required style="width:100%; padding:8px;">
</div>

<div style="margin-bottom:15px;">
    <label>Description</label>
    <textarea name="description" rows="5" required style="width:100%; padding:8px;"></textarea>
</div>

<button type="submit" class="btn btn-primary">Create Ticket</button>
<a href="../dashboard.php" class="btn btn-light">Cancel</a>

</form>
</div>

</div>

<script>
document.getElementById('category').addEventListener('change', function(){
    const pipFields = document.getElementById('pip-fields');
    if (this.value === 'Performance / PIP') {
        pipFields.style.display = 'block';
    } else {
        pipFields.style.display = 'none';
    }
});
</script>

<?php
require_once __DIR__ . '/../../../includes/helper.php';
renderHelper('create');
require_once __DIR__ . '/../../../includes/layout_footer.php'; ?>