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

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

$company_id = $_SESSION['company_id'];

/* =============================
   FILTERS
============================= */
$user_id = $_GET['user_id'] ?? '';
$from    = $_GET['from'] ?? '';
$to      = $_GET['to'] ?? '';

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

/* =============================
   LOAD PIP TICKETS
============================= */
$sql = "
    SELECT t.*, u.full_name
    FROM operations_tickets t
    LEFT JOIN users u ON u.id = t.assigned_to
    WHERE t.company_id = ?
      AND t.category = 'Performance / PIP'
";

$params = [$company_id];

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

if ($from !== '') {
    $sql .= " AND DATE(t.created_at) >= ?";
    $params[] = $from;
}

if ($to !== '') {
    $sql .= " AND DATE(t.created_at) <= ?";
    $params[] = $to;
}

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

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

/* =============================
   SUMMARY
============================= */
$total = count($tickets);
$active = 0;
$completed = 0;
$overdue = 0;

foreach ($tickets as $t) {
    if (in_array($t['status'], ['Resolved','Closed'])) {
        $completed++;
    } else {
        $active++;
    }

    if (
        !empty($t['due_at']) &&
        strtotime($t['due_at']) < time() &&
        !in_array($t['status'], ['Resolved','Closed'])
    ) {
        $overdue++;
    }
}

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

<div class="page-header">
    <h2>PIP Performance Report</h2>
    <p class="page-subtitle">Employee performance tracking with audit trail</p>
</div>

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

    <select name="user_id">
        <option value="">All Employees</option>
        <?php foreach ($users as $u): ?>
            <option value="<?= (int)$u['id'] ?>" <?= ((string)$user_id === (string)$u['id']) ? 'selected' : '' ?>>
                <?= htmlspecialchars($u['full_name']) ?>
            </option>
        <?php endforeach; ?>
    </select>

    <input type="date" name="from" value="<?= htmlspecialchars($from) ?>">
    <input type="date" name="to" value="<?= htmlspecialchars($to) ?>">

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

</form>

<div class="stat-grid">

    <div class="stat-card">
        <h3>Total PIP</h3>
        <p><?= $total ?></p>
    </div>

    <div class="stat-card">
        <h3>Active</h3>
        <p><?= $active ?></p>
    </div>

    <div class="stat-card">
        <h3>Completed</h3>
        <p><?= $completed ?></p>
    </div>

    <div class="stat-card">
        <h3>Overdue</h3>
        <p><?= $overdue ?></p>
    </div>

</div>

<div class="table-wrap">
    <table>
        <thead>
            <tr>
                <th>Ticket</th>
                <th>Employee</th>
                <th>Stage</th>
                <th>Start</th>
                <th>Review</th>
                <th>End</th>
                <th>Status</th>
                <th>Action</th>
            </tr>
        </thead>

        <tbody>
            <?php if (empty($tickets)): ?>
                <tr>
                    <td colspan="8">No PIP records found</td>
                </tr>
            <?php else: ?>

                <?php foreach ($tickets as $t): ?>
                    <?php
                        $stageClass = 'badge-warning';

                        if (($t['pip_stage'] ?? '') === 'Completed' || in_array($t['status'], ['Resolved','Closed'])) {
                            $stageClass = 'badge-success';
                        } elseif (($t['pip_stage'] ?? '') === 'Review') {
                            $stageClass = 'badge-danger';
                        }

                        $assignedUserId = (int)($t['assigned_to'] ?? 0);
                    ?>

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

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

                        <td>
                            <span class="badge <?= $stageClass ?>">
                                <?= htmlspecialchars($t['pip_stage'] ?? 'Active') ?>
                            </span>
                        </td>

                        <td>
                            <?= !empty($t['pip_start_date']) ? date('Y-m-d', strtotime($t['pip_start_date'])) : '-' ?>
                        </td>

                        <td>
                            <?= !empty($t['pip_review_date']) ? date('Y-m-d', strtotime($t['pip_review_date'])) : '-' ?>
                        </td>

                        <td>
                            <?= !empty($t['pip_end_date']) ? date('Y-m-d', strtotime($t['pip_end_date'])) : '-' ?>
                        </td>

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

                        <td>
                            <div style="display:flex; gap:6px; flex-wrap:wrap;">
                                <a href="../tickets/view.php?id=<?= (int)$t['id'] ?>" class="btn btn-dark">
                                    View
                                </a>

                                <?php if ($assignedUserId > 0): ?>
                                    <a href="pip_employee.php?user_id=<?= $assignedUserId ?>" class="btn btn-light">
                                        Employee
                                    </a>

                                    <a href="pip_pdf.php?user_id=<?= $assignedUserId ?>" class="btn btn-primary">
                                        PDF
                                    </a>
                                <?php else: ?>
                                    <span class="badge badge-muted">No employee</span>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>

                <?php endforeach; ?>

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

<?php require_once __DIR__ . '/../../../includes/layout_footer.php'; ?>