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

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

/* DOMPDF */
require_once __DIR__ . '/../../../libs/dompdf/autoload.inc.php';

use Dompdf\Dompdf;

$company_id = $_SESSION['company_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');

/* LOAD TICKETS */
$tStmt = $pdo->prepare("
    SELECT *
    FROM operations_tickets
    WHERE company_id = ?
      AND category = 'Performance / PIP'
      AND (assigned_to = ? OR assigned_to IS NULL)
");
$tStmt->execute([$company_id, $user_id]);
$tickets = $tStmt->fetchAll(PDO::FETCH_ASSOC);

/* =============================
   SCORING SYSTEM
============================= */
$totalScore = 0;
$count = 0;

foreach ($tickets as $t) {

    $stage = $t['pip_stage'] ?? '';

    switch ($stage) {
        case 'Stage 1 – Verbal Warning': $score = 25; break;
        case 'Stage 2 – Written Warning': $score = 50; break;
        case 'Stage 3 – Final Warning': $score = 75; break;
        case 'Review': $score = 90; break;
        case 'Completed': $score = 100; break;
        default: $score = 40;
    }

    $totalScore += $score;
    $count++;
}

$averageScore = $count > 0 ? round($totalScore / $count) : 0;

/* RESULT */
if ($averageScore < 50) {
    $result = "FAIL";
} elseif ($averageScore < 80) {
    $result = "NEEDS IMPROVEMENT";
} else {
    $result = "PASS";
}

/* =============================
   LOAD TIMELINE
============================= */
$timeline = [];

$evtStmt = $pdo->prepare("
    SELECT e.event_type AS title, e.message AS content, e.created_at, u.full_name
    FROM operations_ticket_events e
    LEFT JOIN users u ON u.id = e.created_by
    WHERE e.ticket_id IN (
        SELECT id FROM operations_tickets
        WHERE company_id = ?
          AND category = 'Performance / PIP'
          AND (assigned_to = ? OR assigned_to IS NULL)
    )
");
$evtStmt->execute([$company_id, $user_id]);
$events = $evtStmt->fetchAll(PDO::FETCH_ASSOC);

$cStmt = $pdo->prepare("
    SELECT 'COMMENT' AS title, c.comment AS content, c.created_at, u.full_name
    FROM operations_ticket_comments c
    LEFT JOIN users u ON u.id = c.created_by
    WHERE c.ticket_id IN (
        SELECT id FROM operations_tickets
        WHERE company_id = ?
          AND category = 'Performance / PIP'
          AND (assigned_to = ? OR assigned_to IS NULL)
    )
");
$cStmt->execute([$company_id, $user_id]);
$comments = $cStmt->fetchAll(PDO::FETCH_ASSOC);

$timeline = array_merge($events, $comments);

usort($timeline, function($a, $b){
    return strtotime($b['created_at']) - strtotime($a['created_at']);
});

/* LOGO */
$logoPath = __DIR__ . '/../../../assets/logo.png';
$logo = file_exists($logoPath)
    ? 'data:image/png;base64,'.base64_encode(file_get_contents($logoPath))
    : '';

/* =============================
   HTML
============================= */
$html = '
<style>
body{ font-family: DejaVu Sans; font-size:12px; }
.header{ border-bottom:3px solid #f2531e; margin-bottom:20px; }
.title{ font-size:18px; font-weight:bold; }
.section{ margin-top:20px; }
table{ width:100%; border-collapse:collapse; margin-top:10px;}
th,td{ border:1px solid #ccc; padding:8px; }
th{ background:#f5f5f5; }
.score-box{
    margin-top:15px;
    padding:10px;
    border:2px solid #f2531e;
    background:#fff4e5;
}
</style>

<div class="header">
'.($logo ? '<img src="'.$logo.'" height="40">' : '').'
<div class="title">PIP Performance Report</div>
<strong>Employee:</strong> '.$user['full_name'].'<br>
<strong>Date:</strong> '.date('Y-m-d H:i').'
</div>

<div class="score-box">
<strong>Performance Score:</strong> '.$averageScore.' / 100<br>
<strong>Result:</strong> '.$result.'
</div>

<div class="section">
<strong>PIP Cases</strong>
<table>
<tr>
<th>Ticket</th><th>Stage</th><th>Start</th><th>Review</th><th>End</th><th>Status</th>
</tr>
';

foreach ($tickets as $t) {
    $html .= '<tr>
    <td>'.$t['ticket_number'].'</td>
    <td>'.$t['pip_stage'].'</td>
    <td>'.$t['pip_start_date'].'</td>
    <td>'.$t['pip_review_date'].'</td>
    <td>'.$t['pip_end_date'].'</td>
    <td>'.$t['status'].'</td>
    </tr>';
}

$html .= '</table></div>

<div class="section">
<strong>Activity Timeline</strong>
<table>
<tr><th>Date</th><th>User</th><th>Action</th><th>Details</th></tr>
';

foreach ($timeline as $t) {
    $html .= '<tr>
    <td>'.date('Y-m-d H:i', strtotime($t['created_at'])).'</td>
    <td>'.$t['full_name'].'</td>
    <td>'.$t['title'].'</td>
    <td>'.$t['content'].'</td>
    </tr>';
}

$html .= '</table></div>

<div class="section">
<strong>Manager Notes</strong>
<div style="border:1px solid #ccc;height:100px;"></div>
</div>

<div class="section">
___________________________ Employee Signature<br><br>
___________________________ Manager Signature
</div>
';

/* PDF */
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->render();
$dompdf->stream("PIP_Report.pdf");
exit;