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

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



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

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

/* =============================
   AUTO ESCALATE / AUTO PIP REVIEW
============================= */
ops_escalate_if_overdue($pdo, $company_id);
pip_move_to_review($pdo, $company_id);

/* =============================
   HELPERS
============================= */
function countStat($pdo, $sql, $params){
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    return (int)$stmt->fetchColumn();
}

function performanceScore(int $openCount, int $overdueCount, int $pipCount): int {
    $score = 100 - (($openCount * 2) + ($overdueCount * 5) + ($pipCount * 10));
    if ($score < 0) $score = 0;
    if ($score > 100) $score = 100;
    return $score;
}

function performanceLevel(int $score): array {
    if ($score < 50) {
        return ['label' => 'FAIL', 'color' => '#ef4444'];
    }
    if ($score < 80) {
        return ['label' => 'IMPROVE', 'color' => '#f59e0b'];
    }
    return ['label' => 'PASS', 'color' => '#10b981'];
}

/* =============================
   DASHBOARD STATS
============================= */
$total = countStat($pdo,
    "SELECT COUNT(*) FROM operations_tickets WHERE company_id=?",
    [$company_id]
);

$open = countStat($pdo,
    "SELECT COUNT(*) FROM operations_tickets 
     WHERE company_id=? AND status='Open'",
    [$company_id]
);

$inProgress = countStat($pdo,
    "SELECT COUNT(*) FROM operations_tickets 
     WHERE company_id=? AND status='In Progress'",
    [$company_id]
);

$overdue = countStat($pdo,
    "SELECT COUNT(*) FROM operations_tickets
     WHERE company_id=?
     AND due_at IS NOT NULL
     AND due_at < NOW()
     AND status NOT IN ('Resolved','Closed')",
    [$company_id]
);

/* =============================
   PIP STATS
============================= */
$pipActive = countStat($pdo,
    "SELECT COUNT(*) FROM operations_tickets
     WHERE company_id=?
     AND category='Performance / PIP'
     AND status NOT IN ('Resolved','Closed')",
    [$company_id]
);

$pipOverdue = countStat($pdo,
    "SELECT COUNT(*) FROM operations_tickets
     WHERE company_id=?
     AND category='Performance / PIP'
     AND due_at IS NOT NULL
     AND due_at < NOW()
     AND status NOT IN ('Resolved','Closed')",
    [$company_id]
);

/* =============================
   STAFF UNDER PIP
============================= */
$pipStaffStmt = $pdo->prepare("
    SELECT u.id, u.full_name, COUNT(*) as total
    FROM operations_tickets t
    LEFT JOIN users u ON u.id = t.assigned_to
    WHERE t.company_id = ?
      AND t.category = 'Performance / PIP'
      AND t.status NOT IN ('Resolved','Closed')
    GROUP BY t.assigned_to, u.id, u.full_name
    ORDER BY total DESC
");
$pipStaffStmt->execute([$company_id]);
$pipStaff = $pipStaffStmt->fetchAll(PDO::FETCH_ASSOC);

/* =============================
   STAFF RISK / PERFORMANCE OVERVIEW
============================= */
$riskStmt = $pdo->prepare("
    SELECT 
        u.id,
        u.full_name,

        SUM(CASE WHEN t.status NOT IN ('Resolved','Closed') THEN 1 ELSE 0 END) as open_count,

        SUM(CASE 
            WHEN t.due_at IS NOT NULL 
             AND t.due_at < NOW() 
             AND t.status NOT IN ('Resolved','Closed') 
            THEN 1 ELSE 0 END) as overdue_count,

        SUM(CASE 
            WHEN t.category = 'Performance / PIP'
             AND t.status NOT IN ('Resolved','Closed')
            THEN 1 ELSE 0 END) as pip_count

    FROM operations_tickets t
    LEFT JOIN users u ON u.id = t.assigned_to
    WHERE t.company_id = ?
    GROUP BY u.id, u.full_name
    ORDER BY u.full_name ASC
");
$riskStmt->execute([$company_id]);
$riskStaff = $riskStmt->fetchAll(PDO::FETCH_ASSOC);

/* =============================
   AUTO CREATE PIP (SAFE ENHANCED)
============================= */
foreach ($riskStaff as $r) {

    $staffId = (int)$r['id'];
    if (!$staffId) continue;

    $openCount    = (int)$r['open_count'];
    $overdueCount = (int)$r['overdue_count'];
    $pipCount     = (int)$r['pip_count'];

    $triggerScore = ($openCount * 2) + ($overdueCount * 5) + ($pipCount * 7);

    if ($triggerScore >= 15) {

        $checkStmt = $pdo->prepare("
            SELECT COUNT(*) 
            FROM operations_tickets
            WHERE company_id = ?
              AND assigned_to = ?
              AND category = 'Performance / PIP'
              AND status NOT IN ('Resolved','Closed')
        ");
        $checkStmt->execute([$company_id, $staffId]);
        $existing = (int)$checkStmt->fetchColumn();

        if ($existing === 0) {

            $ticket_number = 'PIP-' . time() . '-' . $staffId;

            $subject = "Auto PIP Trigger - Score {$triggerScore}";
            $description = "System generated PIP.\n\n"
                         . "Trigger Score: {$triggerScore}\n"
                         . "Open Tickets: {$openCount}\n"
                         . "Overdue Tickets: {$overdueCount}\n"
                         . "Existing Active PIP: {$pipCount}\n\n"
                         . "Action Required: Improve performance and reduce overdue workload.";

            $stmt = $pdo->prepare("
                INSERT INTO operations_tickets
                (
                    company_id,
                    tenant_id,
                    ticket_number,
                    source,
                    category,
                    priority,
                    subject,
                    description,
                    status,
                    assigned_to,
                    created_by,
                    created_at,
                    pip_stage,
                    pip_start_date,
                    pip_review_date
                )
                VALUES
                (
                    ?, ?, ?, 'System', 'Performance / PIP', 'High', ?, ?, 'Open', ?, ?, NOW(),
                    'Stage 1 – Verbal Warning', NOW(), DATE_ADD(NOW(), INTERVAL 7 DAY)
                )
            ");

            $stmt->execute([
                $company_id,
                $_SESSION['tenant_id'] ?? $company_id,
                $ticket_number,
                $subject,
                $description,
                $staffId,
                $user_id
            ]);

            $ticketId = (int)$pdo->lastInsertId();

            if ($ticketId > 0) {
                $eventStmt = $pdo->prepare("
                    INSERT INTO operations_ticket_events
                    (ticket_id, event_type, message, created_by, created_at)
                    VALUES (?, 'PIP AUTO', ?, ?, NOW())
                ");
                $eventStmt->execute([
                    $ticketId,
                    "System automatically created PIP. Trigger score: {$triggerScore}",
                    $user_id
                ]);
            }
        }
    }
}

/* =============================
   AUTO CLOSE PIP (SAFE ENHANCED)
============================= */
foreach ($riskStaff as $r) {

    $staffId = (int)$r['id'];
    if (!$staffId) continue;

    $openCount    = (int)$r['open_count'];
    $overdueCount = (int)$r['overdue_count'];
    $pipCount     = (int)$r['pip_count'];

    $triggerScore = ($openCount * 2) + ($overdueCount * 5) + ($pipCount * 7);

    if ($triggerScore < 10) {

        $findCloseStmt = $pdo->prepare("
            SELECT id
            FROM operations_tickets
            WHERE company_id = ?
              AND assigned_to = ?
              AND category = 'Performance / PIP'
              AND status NOT IN ('Resolved','Closed')
        ");
        $findCloseStmt->execute([$company_id, $staffId]);
        $pipToClose = $findCloseStmt->fetchAll(PDO::FETCH_ASSOC);

        if ($pipToClose) {
            $closeStmt = $pdo->prepare("
                UPDATE operations_tickets
                SET status = 'Resolved',
                    pip_stage = 'Completed',
                    pip_end_date = NOW(),
                    updated_at = NOW()
                WHERE company_id = ?
                  AND assigned_to = ?
                  AND category = 'Performance / PIP'
                  AND status NOT IN ('Resolved','Closed')
            ");
            $closeStmt->execute([$company_id, $staffId]);

            $eventStmt = $pdo->prepare("
                INSERT INTO operations_ticket_events
                (ticket_id, event_type, message, created_by, created_at)
                VALUES (?, 'PIP AUTO CLOSE', ?, ?, NOW())
            ");

            foreach ($pipToClose as $pipRow) {
                $eventStmt->execute([
                    (int)$pipRow['id'],
                    "System automatically resolved PIP after performance improved. Trigger score: {$triggerScore}",
                    $user_id
                ]);
            }
        }
    }
}

/* =============================
   PERFORMANCE SUMMARY
============================= */
$performanceAverage = 0;
$passCount = 0;
$improveCount = 0;
$failCount = 0;

if (!empty($riskStaff)) {
    $sum = 0;

    foreach ($riskStaff as $r) {
        $staffScore = performanceScore(
            (int)$r['open_count'],
            (int)$r['overdue_count'],
            (int)$r['pip_count']
        );

        $sum += $staffScore;

        if ($staffScore < 50) {
            $failCount++;
        } elseif ($staffScore < 80) {
            $improveCount++;
        } else {
            $passCount++;
        }
    }

    $performanceAverage = round($sum / count($riskStaff));
}
?>

<div class="page-header">
    <h2>Operations Hub</h2>
    <p class="page-subtitle">Enterprise Operational Control Centre</p>
</div>

<div class="dashboard-grid">

    <div class="stat-card orange">
        <h4>Total Tickets</h4>
        <div class="number"><?= $total ?></div>
    </div>

    <div class="stat-card green">
        <h4>Open</h4>
        <div class="number"><?= $open ?></div>
    </div>

    <div class="stat-card blue">
        <h4>In Progress</h4>
        <div class="number"><?= $inProgress ?></div>
    </div>

    <div class="stat-card red">
        <h4>Overdue</h4>
        <div class="number"><?= $overdue ?></div>
    </div>

    <a href="tickets/index.php?category=Performance%20/%20PIP" style="text-decoration:none;">
        <div class="stat-card orange">
            <h4>Active PIPs</h4>
            <div class="number"><?= $pipActive ?></div>
        </div>
    </a>

    <a href="tickets/index.php?category=Performance%20/%20PIP&overdue=1" style="text-decoration:none;">
        <div class="stat-card red">
            <h4>Overdue PIPs</h4>
            <div class="number"><?= $pipOverdue ?></div>
        </div>
    </a>

    <div class="stat-card">
        <h4>Performance Average</h4>
        <div class="number"><?= $performanceAverage ?>%</div>
    </div>

    <div class="stat-card">
        <h4>Pass / Improve / Fail</h4>
        <div class="number" style="font-size:20px;">
            <?= $passCount ?> / <?= $improveCount ?> / <?= $failCount ?>
        </div>
    </div>

</div>

<div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(320px,1fr)); gap:20px; margin-top:20px;">

    <div style="background:#fff; border-radius:14px; padding:20px; box-shadow:0 4px 14px rgba(0,0,0,0.05);">

        <h4 style="margin:0 0 15px 0;">⚠ Staff Under PIP</h4>

        <?php if (empty($pipStaff)): ?>
            <p style="margin:0; color:#6b7280;">No staff currently under PIP</p>
        <?php else: ?>

            <?php foreach ($pipStaff as $s): ?>
                <?php
                    $staffTicketUrl = "tickets/index.php?assigned=" . (int)$s['id'] . "&category=" . urlencode('Performance / PIP');
                    $staffReportUrl = "reports/pip_employee.php?user_id=" . (int)$s['id'];
                    $staffPdfUrl    = "reports/pip_pdf.php?user_id=" . (int)$s['id'];
                ?>

                <div style="padding:12px 15px; border-bottom:1px solid #eee;">
                    <div style="display:flex; justify-content:space-between; align-items:center; gap:10px;">
                        <div style="font-weight:600;">
                            <?= htmlspecialchars($s['full_name'] ?? 'Unassigned') ?>
                        </div>
                        <div style="color:#f2531e; font-weight:600;">
                            <?= (int)$s['total'] ?> ticket<?= ((int)$s['total'] === 1 ? '' : 's') ?>
                        </div>
                    </div>

                    <?php if (!empty($s['id'])): ?>
                    <div style="margin-top:8px; display:flex; gap:8px; flex-wrap:wrap;">
                        <a href="<?= $staffTicketUrl ?>" style="font-size:12px; color:#111; text-decoration:none;">View Tickets</a>
                        <a href="<?= $staffReportUrl ?>" style="font-size:12px; color:#f2531e; text-decoration:none;">Employee Report</a>
                        <a href="<?= $staffPdfUrl ?>" style="font-size:12px; color:#2563eb; text-decoration:none;">PDF Report</a>
                    </div>
                    <?php endif; ?>
                </div>

            <?php endforeach; ?>

        <?php endif; ?>

    </div>

    <div style="background:#fff; border-radius:14px; padding:20px; box-shadow:0 4px 14px rgba(0,0,0,0.05);">

        <h4 style="margin:0 0 15px 0;">⚠ Staff Performance Overview</h4>

        <?php if (empty($riskStaff)): ?>
            <p style="margin:0; color:#6b7280;">No staff performance data available.</p>
        <?php else: ?>

            <?php foreach ($riskStaff as $r): ?>

                <?php
                    $openCount    = (int)$r['open_count'];
                    $overdueCount = (int)$r['overdue_count'];
                    $pipCount     = (int)$r['pip_count'];

                    $scoreData = performanceLevel(
                        performanceScore($openCount, $overdueCount, $pipCount)
                    );

                    $score = performanceScore($openCount, $overdueCount, $pipCount);
                    $level = $scoreData['label'];
                    $color = $scoreData['color'];

                    $reportUrl = !empty($r['id']) ? "reports/pip_employee.php?user_id=" . (int)$r['id'] : '';
                ?>

                <div style="display:flex; justify-content:space-between; gap:15px; padding:12px 0; border-bottom:1px solid #eee;">
                    <div>
                        <strong><?= htmlspecialchars($r['full_name'] ?? 'Unassigned') ?></strong><br>
                        <small style="color:#6b7280;">
                            Open: <?= $openCount ?> | Overdue: <?= $overdueCount ?> | Active PIP: <?= $pipCount ?>
                        </small>

                        <?php if ($reportUrl): ?>
                        <br>
                        <a href="<?= $reportUrl ?>" style="font-size:12px; color:#f2531e; text-decoration:none;">
                            View Report
                        </a>
                        <?php endif; ?>
                    </div>

                    <div style="text-align:right;">
                        <div style="font-weight:700; color:<?= $color ?>">
                            <?= $level ?>
                        </div>
                        <small>Score: <?= $score ?>/100</small>
                    </div>
                </div>

            <?php endforeach; ?>

        <?php endif; ?>

    </div>

</div>

<div style="margin-top:20px;">
    <a href="tickets/create.php" class="btn btn-primary">+ New Ticket</a>
    <a href="tickets/index.php" class="btn btn-dark">View Queue</a>
    <a href="reports/pip.php" class="btn btn-light">PIP Report</a>
</div>

</div>

<?php
require_once __DIR__ . '/../../includes/helper.php';
renderHelper('dashboard');

require_once __DIR__ . '/../../includes/onboarding.php';
renderOnboarding();

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