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

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

/* =============================
   ENTERPRISE FILTER SYSTEM
============================= */

$company_id = $_SESSION['company_id'];

$search   = $_GET['search'] ?? '';
$status   = $_GET['status'] ?? '';
$priority = $_GET['priority'] ?? '';
$assigned = $_GET['assigned'] ?? '';
$category = $_GET['category'] ?? '';
$overdueFilter  = $_GET['overdue'] ?? '';

$sql = "
    SELECT t.*, u.full_name
    FROM operations_tickets t
    LEFT JOIN users u ON t.assigned_to = u.id
    WHERE t.company_id = ?
";

$params = [$company_id];

if ($search !== '') {
    $sql .= " AND (t.ticket_number LIKE ? OR t.subject LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status !== '') {
    $sql .= " AND t.status = ?";
    $params[] = $status;
}

if ($priority !== '') {
    $sql .= " AND t.priority = ?";
    $params[] = $priority;
}

if ($category !== '') {
    $sql .= " AND t.category = ?";
    $params[] = $category;
}

if ($assigned !== '') {
    if ($assigned === 'unassigned') {
        $sql .= " AND t.assigned_to IS NULL";
    } else {
        $sql .= " AND t.assigned_to = ?";
        $params[] = $assigned;
    }
}

if ($overdueFilter === '1') {
    $sql .= " AND t.due_at IS NOT NULL 
              AND t.due_at < NOW() 
              AND t.status NOT IN ('Resolved','Closed')";
}

$sql .= " ORDER BY t.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

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

<div class="page-header">
    <h2>Ticket Queue</h2>
    <p class="page-subtitle">All operational tickets</p>
</div>

<a href="create.php" class="btn btn-primary">+ New Ticket</a>

<form method="GET" class="filter-card">

    <input type="text" name="search"
           placeholder="Search ticket or subject"
           value="<?= htmlspecialchars($search) ?>">

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

    <select name="priority">
        <option value="">All Priority</option>
        <option value="Low" <?= $priority==='Low'?'selected':'' ?>>Low</option>
        <option value="Medium" <?= $priority==='Medium'?'selected':'' ?>>Medium</option>
        <option value="High" <?= $priority==='High'?'selected':'' ?>>High</option>
        <option value="Critical" <?= $priority==='Critical'?'selected':'' ?>>Critical</option>
    </select>

    <select name="category">
        <option value="">All Category</option>
        <?php
        $categories = ['General','Fault','Installation','Replacement','Billing','Token Issue','Performance / PIP'];
        foreach ($categories as $c):
        ?>
        <option value="<?= $c ?>" <?= $category === $c ? 'selected' : '' ?>>
            <?= $c ?>
        </option>
        <?php endforeach; ?>
    </select>

    <select name="assigned">
        <option value="">All Assigned</option>
        <option value="unassigned" <?= $assigned==='unassigned'?'selected':'' ?>>Unassigned</option>
        <?php foreach ($activeUsers as $u): ?>
        <option value="<?= $u['id'] ?>" <?= $assigned == $u['id'] ? 'selected' : '' ?>>
            <?= htmlspecialchars($u['full_name']) ?>
        </option>
        <?php endforeach; ?>
    </select>

    <label style="display:flex;align-items:center;gap:6px;">
        <input type="checkbox" name="overdue" value="1"
               <?= $overdueFilter==='1'?'checked':'' ?>>
        Overdue Only
    </label>

    <button type="submit" class="btn btn-primary">Apply</button>
    <a href="index.php" class="btn btn-light">Reset</a>

</form>

<div class="table-wrap">
<table>
    <thead>
        <tr>
            <th>Ticket #</th>
            <th>Status</th>
            <th>Priority</th>
            <th>Assigned To</th>
            <th>Category</th>
            <th>Source</th>
            <th>Subject</th>
            <th>Created</th>
        </tr>
    </thead>
    <tbody>
        <?php if (empty($tickets)): ?>
            <tr>
                <td colspan="8">No tickets found.</td>
            </tr>
        <?php else: ?>
            <?php foreach ($tickets as $t): ?>
            <?php $isPIP = ($t['category'] === 'Performance / PIP'); ?>

            <?php
            $statusClass = 'badge-muted';

            switch ($t['status']) {
                case 'Open':
                case 'Assigned':
                case 'Awaiting Customer':
                    $statusClass = 'badge-warning';
                    break;

                case 'In Progress':
                case 'Resolved':
                    $statusClass = 'badge-success';
                    break;

                case 'Escalated':
                    $statusClass = 'badge-danger';
                    break;

                case 'Closed':
                    $statusClass = 'badge-muted';
                    break;
            }

            $rowOverdue = false;
            if (
                $t['due_at'] &&
                !in_array($t['status'], ['Resolved','Closed']) &&
                strtotime($t['due_at']) < time()
            ) {
                $rowOverdue = true;
            }
            ?>

            <tr style="<?php 
                if ($isPIP) {
                    echo 'background:#fff4e5; border-left:4px solid #f2531e;';
                } elseif ($rowOverdue) {
                    echo 'background:#fdecea;';
                }
            ?>">
                <td>
                    <a href="view.php?id=<?= $t['id'] ?>">
                        <?= htmlspecialchars($t['ticket_number']) ?>
                    </a>
                </td>

                <td>
                    <span class="badge <?= $statusClass ?>">
                        <?= htmlspecialchars($t['status']) ?>
                    </span>
                </td>

                <td><?= htmlspecialchars($t['priority']) ?></td>

                <td>
                    <?= $t['full_name']
                        ? htmlspecialchars($t['full_name'])
                        : '<span class="badge badge-muted">Unassigned</span>' ?>
                </td>

                <td>
                    <?php if ($t['category'] === 'Performance / PIP'): ?>
                        <div style="display:flex;flex-direction:column;gap:4px;">
                            <span style="
                                background:#f2531e;
                                color:#fff;
                                padding:4px 10px;
                                border-radius:20px;
                                font-size:12px;
                                font-weight:600;
                                width:fit-content;
                            ">
                                ⚠ PIP
                            </span>

                            <span style="font-size:12px;color:#6b7280;">
                                <?= htmlspecialchars($t['pip_stage'] ?? 'Active') ?>
                            </span>

                            <span style="font-size:11px;color:#9ca3af;">
                                <?= !empty($t['pip_review_date'])
                                    ? date('Y-m-d', strtotime($t['pip_review_date']))
                                    : 'No review date' ?>
                            </span>
                        </div>
                    <?php else: ?>
                        <?= htmlspecialchars($t['category']) ?>
                    <?php endif; ?>
                </td>

                <td><?= htmlspecialchars($t['source']) ?></td>
                <td><?= htmlspecialchars($t['subject']) ?></td>
                <td><?= date('Y-m-d H:i', strtotime($t['created_at'])) ?></td>
            </tr>

            <?php endforeach; ?>
        <?php endif; ?>
    </tbody>
</table>
</div>

</div>

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