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

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

$company_id = $_SESSION['company_id'];
$user_id    = $_SESSION['user_id'];

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id <= 0) {
    header("Location: index.php");
    exit;
}

/* =============================
   LOAD TICKET (TENANT SAFE)
============================= */
$tStmt = $pdo->prepare("
    SELECT t.*, u.full_name AS assigned_name
    FROM operations_tickets t
    LEFT JOIN users u ON u.id = t.assigned_to
    WHERE t.id = ? AND t.company_id = ?
    LIMIT 1
");
$tStmt->execute([$id, $company_id]);
$ticket = $tStmt->fetch(PDO::FETCH_ASSOC);

if (!$ticket) {
    header("Location: index.php");
    exit;
}

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

/* =============================
   HANDLE UPDATE SUBMISSION
============================= */
$errors = [];
$success = null;

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

    $new_status   = $_POST['status'] ?? $ticket['status'];
    $new_priority = $_POST['priority'] ?? $ticket['priority'];
    $new_assigned = $_POST['assigned_to'] ?? '';
    $new_due_at   = $_POST['due_at'] ?? '';

    $new_assigned = ($new_assigned === '' ? null : (int)$new_assigned);
    $new_due_at   = ($new_due_at === '' ? null : $new_due_at);

    /* =============================
       PIP UPDATE
    ============================== */
    $new_pip_stage = $_POST['pip_stage'] ?? $ticket['pip_stage'];
    $new_pip_review_date = $_POST['pip_review_date'] ?? $ticket['pip_review_date'];

    $comment_text = trim($_POST['comment'] ?? '');
    $visibility   = ($_POST['visibility'] ?? 'INTERNAL') === 'PUBLIC' ? 'PUBLIC' : 'INTERNAL';

    try {
        $pdo->beginTransaction();

        /* UPDATE TICKET */
        $updateStmt = $pdo->prepare("
            UPDATE operations_tickets
            SET status = ?,
                priority = ?,
                assigned_to = ?,
                due_at = ?,
                pip_stage = ?,
                pip_review_date = ?,
                updated_at = NOW()
            WHERE id = ? AND company_id = ?
            LIMIT 1
        ");
        $updateStmt->execute([
            $new_status,
            $new_priority,
            $new_assigned,
            $new_due_at,
            $new_pip_stage,
            $new_pip_review_date,
            $id,
            $company_id
        ]);

        /* =============================
           SMART EVENT LOGGING
        ============================== */

        if ($new_status !== $ticket['status']) {
            $pdo->prepare("
                INSERT INTO operations_ticket_events
                (ticket_id, event_type, message, created_by, created_at)
                VALUES (?, 'STATUS', ?, ?, NOW())
            ")->execute([$id, "Status changed to {$new_status}", $user_id]);
        }

        if ($new_assigned != $ticket['assigned_to']) {
            $pdo->prepare("
                INSERT INTO operations_ticket_events
                (ticket_id, event_type, message, created_by, created_at)
                VALUES (?, 'ASSIGNMENT', 'Assignment updated', ?, NOW())
            ")->execute([$id, $user_id]);
        }

        if ($new_pip_stage !== $ticket['pip_stage']) {
            $pdo->prepare("
                INSERT INTO operations_ticket_events
                (ticket_id, event_type, message, created_by, created_at)
                VALUES (?, 'PIP UPDATE', ?, ?, NOW())
            ")->execute([$id, "PIP stage changed to {$new_pip_stage}", $user_id]);
        }

        /* COMMENT */
        if ($comment_text !== '') {

            $pdo->prepare("
                INSERT INTO operations_ticket_comments
                (ticket_id, visibility, comment, created_by, created_at)
                VALUES (?, ?, ?, ?, NOW())
            ")->execute([
                $id,
                $visibility,
                $comment_text,
                $user_id
            ]);

            $pdo->prepare("
                INSERT INTO operations_ticket_events
                (ticket_id, event_type, message, created_by, created_at)
                VALUES (?, 'COMMENT', ?, ?, NOW())
            ")->execute([
                $id,
                "Comment added ({$visibility})",
                $user_id
            ]);
        }

        $pdo->commit();
        $success = "Ticket updated successfully.";

        /* RELOAD */
        $tStmt->execute([$id, $company_id]);
        $ticket = $tStmt->fetch(PDO::FETCH_ASSOC);

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $errors[] = "Update failed. Please try again.";
    }
}

/* =============================
   LOAD COMMENTS
============================= */
$commentsStmt = $pdo->prepare("
    SELECT c.*, u.full_name
    FROM operations_ticket_comments c
    LEFT JOIN users u ON u.id = c.created_by
    WHERE c.ticket_id = ?
    ORDER BY c.created_at DESC
");
$commentsStmt->execute([$id]);
$comments = $commentsStmt->fetchAll(PDO::FETCH_ASSOC);

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

<div class="page-header">
    <h2>Update Ticket</h2>
    <p class="page-subtitle">
        <?= htmlspecialchars($ticket['ticket_number']) ?> • <?= htmlspecialchars($ticket['subject']) ?>
    </p>
</div>

<?php if (!empty($errors)): ?>
<div class="alert alert-error"><?= htmlspecialchars(implode(" | ", $errors)) ?></div>
<?php endif; ?>

<?php if ($success): ?>
<div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>

<div class="card-form">

<form method="POST">

<label>Status</label>
<select name="status" required>
<?php foreach (['Open','Assigned','In Progress','Awaiting Customer','Escalated','Resolved','Closed'] as $s): ?>
<option value="<?= $s ?>" <?= ($ticket['status'] === $s ? 'selected' : '') ?>>
<?= $s ?>
</option>
<?php endforeach; ?>
</select>

<label>Priority</label>
<select name="priority" required>
<?php foreach (['Low','Medium','High','Critical'] as $p): ?>
<option value="<?= $p ?>" <?= ($ticket['priority'] === $p ? 'selected' : '') ?>>
<?= $p ?>
</option>
<?php endforeach; ?>
</select>

<label>Assign To</label>
<select name="assigned_to">
<option value="">Unassigned</option>
<?php foreach ($users as $u): ?>
<option value="<?= $u['id'] ?>" <?= ((string)$ticket['assigned_to'] === (string)$u['id']) ? 'selected' : '' ?>>
<?= htmlspecialchars($u['full_name']) ?>
</option>
<?php endforeach; ?>
</select>

<label>Due Date (SLA)</label>
<input type="datetime-local" name="due_at"
value="<?= $ticket['due_at'] ? date('Y-m-d\TH:i', strtotime($ticket['due_at'])) : '' ?>">

<?php if ($ticket['category'] === 'Performance / PIP'): ?>
<hr>
<h4>PIP Management</h4>

<label>PIP Stage</label>
<select name="pip_stage">
<?php foreach ([
'Stage 1 – Verbal Warning',
'Stage 2 – Written Warning',
'Stage 3 – Final Warning',
'Review',
'Completed'
] as $stage): ?>
<option value="<?= $stage ?>" <?= ($ticket['pip_stage'] === $stage ? 'selected' : '') ?>>
<?= $stage ?>
</option>
<?php endforeach; ?>
</select>

<label>PIP Review Date</label>
<input type="date" name="pip_review_date"
value="<?= $ticket['pip_review_date'] ? date('Y-m-d', strtotime($ticket['pip_review_date'])) : '' ?>">
<?php endif; ?>

<label>Add Comment</label>
<textarea name="comment" rows="4"></textarea>

<label>Comment Visibility</label>
<select name="visibility">
<option value="INTERNAL">Internal</option>
<option value="PUBLIC">Public</option>
</select>

<div style="display:flex; gap:10px;">
<button type="submit" class="btn btn-primary">Save Changes</button>
<a href="view.php?id=<?= $id ?>" class="btn btn-dark">Back to View</a>
<a href="index.php" class="btn btn-light">Back to Queue</a>
</div>

</form>

</div>

<div style="margin-top:20px;" class="table-wrap">
<table>
<thead>
<tr>
<th>Comment</th>
<th>Visibility</th>
<th>By</th>
<th>When</th>
</tr>
</thead>
<tbody>
<?php if (!$comments): ?>
<tr><td colspan="4">No comments yet.</td></tr>
<?php else: ?>
<?php foreach ($comments as $c): ?>
<tr>
<td><?= nl2br(htmlspecialchars($c['comment'])) ?></td>
<td><?= htmlspecialchars($c['visibility']) ?></td>
<td><?= htmlspecialchars($c['full_name'] ?? 'System') ?></td>
<td><?= date('Y-m-d H:i', strtotime($c['created_at'])) ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>

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