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

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

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

$user_id = (int)($_GET['user_id'] ?? 0);

if ($user_id <= 0) exit('Invalid employee');

/* =============================
   LOAD USER
============================= */
$userStmt = $pdo->prepare("
SELECT id, full_name 
FROM users 
WHERE id = ? AND company_id = ?
");
$userStmt->execute([$user_id, $company_id]);
$user = $userStmt->fetch(PDO::FETCH_ASSOC);

if (!$user) exit('User not found');

/* =============================
   SAVE REVIEW
============================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $notes = trim($_POST['notes'] ?? '');
    $scoreInput = (int)($_POST['score'] ?? 0);

    $result = 'PASS';
    if ($scoreInput < 50) $result = 'FAIL';
    elseif ($scoreInput < 70) $result = 'IMPROVE';

    $stmt = $pdo->prepare("
        INSERT INTO pip_reviews
        (company_id, user_id, review_date, manager_notes, score, result, created_by)
        VALUES (?, ?, NOW(), ?, ?, ?, ?)
    ");

    $stmt->execute([
        $company_id,
        $user_id,
        $notes,
        $scoreInput,
        $result,
        $manager_id
    ]);
}

/* =============================
   LOAD ALL TICKETS
============================= */
$stmt = $pdo->prepare("
SELECT *
FROM operations_tickets
WHERE company_id = ?
AND assigned_to = ?
ORDER BY created_at DESC
");
$stmt->execute([$company_id, $user_id]);
$tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* =============================
   PERFORMANCE CALCULATION
============================= */
$openCount = 0;
$overdueCount = 0;
$pipCount = 0;

foreach ($tickets as $t) {

    if (!in_array($t['status'], ['Resolved','Closed'])) {
        $openCount++;
    }

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

    if ($t['category'] === 'Performance / PIP' &&
        !in_array($t['status'], ['Resolved','Closed'])) {
        $pipCount++;
    }
}

$score = 100 - (($openCount * 2) + ($overdueCount * 5) + ($pipCount * 10));
if ($score < 0) $score = 0;

/* LEVEL */
$level = 'PASS';
$color = '#16a34a';

if ($score < 50) {
    $level = 'FAIL';
    $color = '#dc2626';
} elseif ($score < 80) {
    $level = 'IMPROVE';
    $color = '#f59e0b';
}

/* =============================
   LOAD REVIEWS (🔥 THIS WAS MISSING)
============================= */
$reviewStmt = $pdo->prepare("
SELECT r.*, u.full_name
FROM pip_reviews r
LEFT JOIN users u ON u.id = r.created_by
WHERE r.company_id = ?
AND r.user_id = ?
ORDER BY r.review_date DESC
");
$reviewStmt->execute([$company_id, $user_id]);
$reviews = $reviewStmt->fetchAll(PDO::FETCH_ASSOC);

/* =============================
   SCORE TREND
============================= */
$trend = 'N/A';
$trendColor = '#6b7280';

if (count($reviews) >= 2) {
    $latest = (int)$reviews[0]['score'];
    $previous = (int)$reviews[1]['score'];

    if ($latest > $previous) {
        $trend = 'Improving';
        $trendColor = '#10b981';
    } elseif ($latest < $previous) {
        $trend = 'Declining';
        $trendColor = '#ef4444';
    } else {
        $trend = 'Stable';
        $trendColor = '#f59e0b';
    }
}

/* =============================
   AUTO WARNINGS
============================= */
$warning = null;

$failCount = 0;
foreach (array_slice($reviews, 0, 3) as $r) {
    if ($r['result'] === 'FAIL') $failCount++;
}

if ($failCount >= 3) {
    $warning = "⚠ FINAL WARNING: Immediate action required";
} elseif ($failCount == 2) {
    $warning = "⚠ WARNING: Performance declining";
} elseif ($failCount == 1) {
    $warning = "⚠ NOTICE: Monitor performance";
}

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

<div class="page-header">
    <h2>PIP Report: <?= htmlspecialchars($user['full_name']) ?></h2>
</div>

<a href="pip_print.php?user_id=<?= $user_id ?>" class="btn btn-dark">Print</a>
<a href="pip_pdf.php?user_id=<?= $user_id ?>" class="btn btn-primary">Download PDF</a>

<!-- TREND -->
<div style="margin-top:15px; padding:15px; border-left:4px solid <?= $trendColor ?>; background:#f9fafb;">
    <strong>Trend:</strong> 
    <span style="color:<?= $trendColor ?>; font-weight:600;">
        <?= $trend ?>
    </span>

    <?php if ($warning): ?>
        <div style="margin-top:8px; color:#dc2626; font-weight:600;">
            <?= $warning ?>
        </div>
    <?php endif; ?>
</div>

<!-- SUMMARY -->
<div style="margin-top:20px; padding:15px; background:#f9fafb;">
    Open: <?= $openCount ?> |
    Overdue: <?= $overdueCount ?> |
    PIP: <?= $pipCount ?><br><br>

    <strong style="color:<?= $color ?>">
        Score: <?= $score ?>/100 (<?= $level ?>)
    </strong>
</div>

<!-- ADD REVIEW -->
<div class="card-form" style="margin-top:20px;">
<h3>Add Weekly Review</h3>

<form method="POST">
<label>Score</label>
<input type="number" name="score" required min="0" max="100">

<label>Manager Notes</label>
<textarea name="notes" rows="4" required></textarea>

<button class="btn btn-primary">Save Review</button>
</form>
</div>

<!-- HISTORY -->
<div style="margin-top:30px;">
<h3>Review History</h3>

<?php if (!$reviews): ?>
<p>No reviews yet</p>
<?php else: ?>

<table class="table-wrap">
<tr>
<th>Date</th>
<th>Score</th>
<th>Result</th>
<th>Notes</th>
<th>Manager</th>
</tr>

<?php foreach ($reviews as $r): ?>
<tr>
<td><?= date('Y-m-d H:i', strtotime($r['review_date'])) ?></td>
<td><?= $r['score'] ?></td>
<td><?= $r['result'] ?></td>
<td><?= nl2br(htmlspecialchars($r['manager_notes'])) ?></td>
<td><?= htmlspecialchars($r['full_name']) ?></td>
</tr>
<?php endforeach; ?>

</table>

<?php endif; ?>

</div>

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