<?php
session_start();
require_once '../config/db.php';

// This page renders a printable HTML summary and uses JS to generate a PDF.
// It can be opened from the mobile app to trigger a PDF download.

$memberId = isset($_GET['user_id']) ? (int) $_GET['user_id'] : 0;
$yearParam = isset($_GET['year']) ? $_GET['year'] : '0';
$isAllYears = ($yearParam === 'all' || $yearParam === '0' || (int) $yearParam === 0);
$year = $isAllYears ? 0 : (int) $yearParam;
$matchIdFilter = isset($_GET['match_id']) ? (int) $_GET['match_id'] : 0;

if ($memberId <= 0) {
    die("Invalid Member ID");
}

// 1. Fetch Member Info
$stmtMember = $pdo->prepare("SELECT id, first_name, last_name, nroi_id, area, profile_photo FROM users WHERE id = ? AND status = 'approved'");
$stmtMember->execute([$memberId]);
$member = $stmtMember->fetch(PDO::FETCH_ASSOC);

if (!$member) {
    die("Member not found or not approved.");
}

$userFullName = trim($member['first_name'] . ' ' . $member['last_name']);
$userNroiId = $member['nroi_id'] ?? '---';
$userArea = $member['area'] ?? '---';
$profilePhoto = $member['profile_photo'] ?? '';

// 2. Fetch AC for this user's area
$acId = 0;
$acName = "Area Coordinator";
$acSigPath = "";
$stmtAC = $pdo->prepare("SELECT id, first_name, last_name FROM users WHERE role = 'AC' AND area = ? AND status = 'approved' LIMIT 1");
$stmtAC->execute([$userArea]);
$ac = $stmtAC->fetch(PDO::FETCH_ASSOC);

if ($ac) {
    $acId = $ac['id'];
    $acName = $ac['first_name'] . ' ' . $ac['last_name'];
    $sigDir = __DIR__ . '/../storage/officers_signature/';
    $acFiles = glob($sigDir . 'officer_' . $acId . '_*');
    if (!empty($acFiles)) {
        // Sort by time to get the latest one
        usort($acFiles, fn($a, $b) => filemtime($b) - filemtime($a));
        $acSigPath = 'storage/officers_signature/' . basename($acFiles[0]);
    }
}

// 3. Fetch Points Data including Manual Entries
$matches = [];
// Dynamic role recognition for all assignment tables
$roleCases = "";
try {
    $stmtTables = $pdo->query("SHOW TABLES LIKE 'match_%_assignments'");
    $assignmentTables = $stmtTables->fetchAll(PDO::FETCH_COLUMN);

    usort($assignmentTables, function ($a, $b) {
        $priority = ['match_states_assignments' => 1, 'match_stats_assignments' => 2, 'match_chrono_assignments' => 3, 'match_equipment_check_assignments' => 4];
        $pA = $priority[$a] ?? 99;
        $pB = $priority[$b] ?? 99;
        return $pA - $pB;
    });

    foreach ($assignmentTables as $tbl) {
        if ($tbl === 'match_range_master_assignments')
            continue;
        $roleCases .= "               WHEN (SELECT role FROM `$tbl` WHERE match_id = m.id AND submitted_by = mp.user_id LIMIT 1) > '' 
                    THEN (SELECT role FROM `$tbl` WHERE match_id = m.id AND submitted_by = mp.user_id LIMIT 1)\n";
    }
} catch (Exception $e) {
}

$actualMatchesQuery = "
    SELECT mp.id as mp_id, mp.points, mp.rm_signature, mp.created_at as submitted_at,
           m.id as match_id, m.match_name, m.match_level, m.start_date, m.end_date, m.location, m.range_master as disciplines, m.rm_name,
           CASE 
               WHEN m.rm_id = ? THEN 'Range Master'
               WHEN (SELECT role FROM match_range_master_assignments WHERE match_id = m.id AND submitted_by = mp.user_id LIMIT 1) IS NOT NULL 
                    AND (SELECT role FROM match_range_master_assignments WHERE match_id = m.id AND submitted_by = mp.user_id LIMIT 1) != '' 
                     THEN (CASE 
                         WHEN (SELECT role FROM match_range_master_assignments WHERE match_id = m.id AND submitted_by = mp.user_id LIMIT 1) = 'Area Chief Officer' THEN 'Area Chief Range Officer'
                         ELSE (SELECT role FROM match_range_master_assignments WHERE match_id = m.id AND submitted_by = mp.user_id LIMIT 1)
                     END)
$roleCases               ELSE '---'
           END as assigned_role,
           0 as is_manual
    FROM match_points mp
    JOIN match_schedules m ON mp.match_id = m.id
    WHERE mp.user_id = ?
";
$actualParams = [$memberId, $memberId];

if ($matchIdFilter > 0) {
    $actualMatchesQuery .= " AND mp.match_id = ?";
    $actualParams[] = $matchIdFilter;
} else if (!$isAllYears) {
    $actualMatchesQuery .= " AND YEAR(m.start_date) = ?";
    $actualParams[] = $year;
}

$stmtActual = $pdo->prepare($actualMatchesQuery);
$stmtActual->execute($actualParams);
$matches = $stmtActual->fetchAll(PDO::FETCH_ASSOC);

if ($matchIdFilter <= 0) {
    $queryManual = "
        SELECT id as mp_id, points, NULL as rm_signature, created_at as submitted_at,
               NULL as match_id, match_name, level as match_level, 
               CASE 
                   WHEN month IS NOT NULL AND month > 0 THEN CAST(CONCAT(year, '-', LPAD(month, 2, '0'), '-01') AS DATE)
                   ELSE CAST(CONCAT(year, '-01-01') AS DATE)
               END as start_date,
               CASE 
                   WHEN month IS NOT NULL AND month > 0 THEN CAST(CONCAT(year, '-', LPAD(month, 2, '0'), '-01') AS DATE)
                   ELSE CAST(CONCAT(year, '-01-01') AS DATE)
               END as end_date,
               location, discipline as disciplines, 'Manual Entry' as rm_name,
               role as assigned_role,
               1 as is_manual,
               month, year
        FROM manual_match_points
        WHERE user_id = ?
    ";
    $paramsManual = [$memberId];
    if (!$isAllYears) {
        $queryManual .= " AND year = ?";
        $paramsManual[] = $year;
    }
    $stmtManual = $pdo->prepare($queryManual);
    $stmtManual->execute($paramsManual);
    $manualMatches = $stmtManual->fetchAll(PDO::FETCH_ASSOC);
    foreach ($manualMatches as $row) {
        $matches[] = $row;
    }
}

// Sort by date DESC
usort($matches, function ($a, $b) {
    return strtotime($b['start_date']) - strtotime($a['start_date']);
});

$totalPoints = 0;
$roleStats = [];
foreach ($matches as $m) {
    $totalPoints += (float) $m['points'];
    $role = $m['assigned_role'] ?? '---';
    if ($role != '---') {
        $roleStats[$role] = ($roleStats[$role] ?? 0) + 1;
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Match Point Card Summary — <?php echo htmlspecialchars($userFullName); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
            margin: 0;
            padding: 0;
            background: #f1f5f9;
            color: #1e293b;
        }

        #pdfContent {
            background: #fff;
            width: 800px;
            margin: 40px auto;
            padding: 50px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            position: relative;
            min-height: 1000px;
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
            border-bottom: 3px solid #1e3a8a;
            padding-bottom: 30px;
            position: relative;
        }

        .header img.nroi-logo {
            height: 100px;
            margin-bottom: 15px;
        }

        .header h1 {
            font-size: 1.8rem;
            margin: 0;
            color: #1e3a8a;
            text-transform: uppercase;
            letter-spacing: -0.01em;
            font-weight: 800;
        }

        .header p {
            margin: 8px 0 0 0;
            font-size: 1rem;
            color: #64748b;
            font-weight: 600;
            text-transform: uppercase;
        }

        .profile-pic-container {
            width: 120px;
            height: 120px;
            border: 3px solid #e2e8f0;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f8fafc;
            margin-left: 20px;
            flex-shrink: 0;
        }

        .profile-pic-container img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .role-summary {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
            margin-bottom: 30px;
        }

        .role-box {
            background: #f1f5f9;
            padding: 12px;
            border-radius: 8px;
            text-align: center;
            border: 1px solid #e2e8f0;
        }

        .role-name {
            font-size: 0.75rem;
            color: #64748b;
            font-weight: 700;
            text-transform: uppercase;
            margin-bottom: 5px;
            display: block;
        }

        .role-count {
            font-size: 1.25rem;
            font-weight: 800;
            color: #1e3a8a;
        }

        .user-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 30px;
            font-size: 0.95rem;
        }

        .info-item {
            display: flex;
            gap: 8px;
        }

        .info-label {
            font-weight: 700;
            color: #64748b;
            min-width: 80px;
        }

        .total-box {
            background: #f8fafc;
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 30px;
            border-left: 5px solid #16a34a;
        }

        .total-label {
            font-size: 0.85rem;
            font-weight: 600;
            color: #64748b;
            text-transform: uppercase;
        }

        .total-val {
            font-size: 2rem;
            font-weight: 800;
            color: #16a34a;
        }

        .matches-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.85rem;
        }

        .matches-table th {
            background: #f1f5f9;
            text-align: left;
            padding: 12px;
            font-weight: 700;
            border-bottom: 2px solid #e2e8f0;
        }

        .matches-table td {
            padding: 12px;
            border-bottom: 1px solid #f1f5f9;
            vertical-align: top;
        }

        .points-col {
            font-weight: 800;
            color: #16a34a;
            font-size: 1rem;
        }

        .sig-container {
            text-align: center;
            min-width: 140px;
        }

        .sig-img {
            max-width: 120px;
            max-height: 50px;
            display: block;
            margin: 0 auto;
        }

        .sig-name {
            font-weight: 700;
            font-size: 0.8rem;
            margin-top: 5px;
            border-top: 1px solid #e2e8f0;
            padding-top: 3px;
        }

        .sig-time {
            font-size: 0.7rem;
            color: #64748b;
            line-height: 1.2;
        }

        .footer-signatures {
            margin-top: 40px;
            padding-top: 20px;
            page-break-inside: avoid;
        }

        .ac-sig-box {
            text-align: center;
            min-width: 250px;
        }

        #loadingOverlay {
            position: fixed;
            inset: 0;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #1e3a8a;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        @media print {
            body {
                background: #fff;
            }

            #pdfContent {
                margin: 0;
                box-shadow: none;
                border: none;
                width: 100%;
            }
        }
    </style>
</head>

<body>

    <div id="loadingOverlay">
        <div class="spinner"></div>
        <p style="margin-top:15px; font-weight:600; color:#1e3a8a;">Generating PDF...</p>
    </div>

    <div id="pdfContent">
        <div class="header">
            <img src="../assets/images/nroi_logo.png" alt="NROI Logo" class="nroi-logo">
            <h1>NATIONAL RANGE OFFICERS INSTITUTE</h1>
            <p>Official User Points Card Summary Report <?php echo $isAllYears ? '(All Years)' : "($year)"; ?></p>
        </div>

        <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 30px;">
            <div class="user-info" style="margin-bottom: 0; flex: 1;">
                <div class="info-item">
                    <span class="info-label">Name:</span>
                    <span><?php echo htmlspecialchars($userFullName); ?></span>
                </div>
                <div class="info-item">
                    <span class="info-label">Year:</span>
                    <span><?php echo $isAllYears ? 'All Years' : $year; ?></span>
                </div>
                <div class="info-item">
                    <span class="info-label">NROI ID:</span>
                    <span><?php echo htmlspecialchars($userNroiId); ?></span>
                </div>
                <div class="info-item">
                    <span class="info-label">Area:</span>
                    <span><?php echo htmlspecialchars($userArea); ?></span>
                </div>
            </div>
            <?php if (!empty($profilePhoto)): ?>
                <div class="profile-pic-container">
                    <img src="../<?php echo htmlspecialchars($profilePhoto); ?>" alt="Profile Picture">
                </div>
            <?php endif; ?>
        </div>

        <div class="total-box">
            <div class="total-label">Total Points Earned (<?php echo $isAllYears ? 'All Years' : $year; ?>)</div>
            <div class="total-val"><?php echo number_format($totalPoints, 2); ?> pts</div>
        </div>


        <table class="matches-table">
            <thead>
                <tr>
                    <th style="width:30px">#</th>
                    <th>Match Name</th>
                    <th>Location</th>
                    <th>Discipline</th>
                    <th>Date & Level</th>
                    <th>Points</th>
                    <th style="text-align:center">RM Signature</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($matches)): ?>
                    <tr>
                        <td colspan="7" style="text-align:center; padding:50px;">No match records found for this period.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($matches as $i => $row): ?>
                        <tr <?php echo !empty($row['is_manual']) ? 'style="background: #f0f9ff;"' : ''; ?>>
                            <td><?php echo $i + 1; ?></td>
                            <td>
                                <div style="font-weight:700; color:#1e3a8a;">
                                    <?php echo htmlspecialchars($row['match_name']); ?>
                                </div>
                                <?php if (!empty($row['is_manual'])): ?>
                                    <div style="margin-top:4px;">
                                        <span
                                            style="background:#dbeafe; color:#1e40af; padding:1px 5px; border-radius:4px; font-weight:700; font-size:0.65rem; text-transform:uppercase;">Prev.
                                            Match</span>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div style="color:#64748b; font-size:0.8rem;">
                                    <?php echo htmlspecialchars($row['location'] ?: '---'); ?>
                                </div>
                            </td>
                            <td>
                                <div style="color:#64748b; font-size:0.75rem; font-weight: 500;">
                                    <?php echo !empty($row['disciplines']) ? str_replace(', ', '<br>', htmlspecialchars($row['disciplines'])) : '---'; ?>
                                </div>
                            </td>
                            <td>
                                <div>
                                    <?php
                                    if (!empty($row['is_manual'])) {
                                        if (!empty($row['month']) && $row['month'] > 0) {
                                            echo date('F', mktime(0, 0, 0, $row['month'], 10)) . ' ' . date('Y', strtotime($row['start_date']));
                                        } else {
                                            echo date('Y', strtotime($row['start_date']));
                                        }
                                    } else {
                                        echo date('M d, Y', strtotime($row['start_date']));
                                    }
                                    ?>
                                </div>
                                <div style="margin-top:4px;">
                                    <span
                                        style="background:#e0f2fe; color:#0369a1; padding:2px 6px; border-radius:4px; font-weight:700; font-size:0.7rem;">
                                        LVL <?php echo preg_replace('/\D/', '', $row['match_level']); ?>
                                    </span>
                                </div>
                            </td>
                            <td class="points-col">+<?php echo number_format($row['points'], 2); ?></td>
                            <td>
                                <div class="sig-container">
                                    <?php if (!empty($row['rm_signature'])): ?>
                                        <img src="../<?php echo htmlspecialchars($row['rm_signature']); ?>" class="sig-img"
                                            alt="Sig">
                                        <div class="sig-name">
                                            <?php echo htmlspecialchars(!empty($row['rm_name']) ? $row['rm_name'] : 'Range Master'); ?>
                                        </div>
                                        <div class="sig-time">
                                            <?php echo date('M d, Y', strtotime($row['submitted_at'])); ?><br>
                                            <?php echo date('h:i A', strtotime($row['submitted_at'])); ?>
                                        </div>
                                    <?php elseif (!empty($row['is_manual'])): ?>
                                        <div style="color:#94a3b8; font-style:italic; font-size: 0.7rem;">Manual Entry</div>
                                    <?php else: ?>
                                        <div style="color:#cbd5e1; font-style:italic;">---</div>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- AC Signature at lower right -->
        <div class="footer-signatures">
            <div
                style="display: flex; justify-content: space-between; align-items: flex-end; width: 100%; border-top: 2px solid #1e3a8a; padding-top: 30px;">
                <div style="text-align: left; color: #64748b; font-size: 0.9rem; line-height: 1.5;">
                    <div
                        style="font-weight: 700; color: #94a3b8; text-transform: uppercase; font-size: 0.8rem; margin-bottom: 4px;">
                        Report Metadata</div>
                    <div style="display: flex; flex-direction: column;">
                        <span>Generated by NROI Portal</span>
                        <span
                            style="font-weight: 800; color: #475569; font-size: 1rem;"><?php echo date('F d, Y | H:i:s'); ?></span>
                        <span style="font-weight: 600;">Official Report</span>
                    </div>
                </div>

                <div class="ac-sig-box">
                    <?php if ($acSigPath): ?>
                        <img src="../<?php echo htmlspecialchars($acSigPath); ?>"
                            style="max-width: 250px; max-height: 100px; display: block; margin: 0 auto;" alt="AC Signature">
                    <?php else: ?>
                        <div style="height: 60px;"></div>
                    <?php endif; ?>
                    <div
                        style="border-top: 2px solid #1e293b; font-weight: 800; font-size: 1.2rem; text-transform: uppercase; margin-top: 5px; padding-top: 5px;">
                        <?php echo htmlspecialchars($acName); ?>
                    </div>
                    <div style="font-size: 0.95rem; color: #64748b; font-weight: 700;">Area Coordinator</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts for PDF Generation -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script>
        window.onload = function () {
            const el = document.getElementById('pdfContent');
            const overlay = document.getElementById('loadingOverlay');

            // Give a small delay to ensure fonts and images are loaded
            setTimeout(() => {
                html2canvas(el, {
                    scale: 2,
                    useCORS: true,
                    allowTaint: true,
                    backgroundColor: '#ffffff',
                    windowWidth: 800
                }).then(canvas => {
                    const { jsPDF } = window.jspdf;
                    const pdf = new jsPDF('p', 'mm', 'a4');

                    const imgW = 210; // A4 width in mm
                    const pageHeight = 297; // A4 height in mm
                    const imgH = canvas.height * imgW / canvas.width;
                    let heightLeft = imgH;

                    const imgData = canvas.toDataURL('image/png');
                    let position = 0;

                    // First page
                    pdf.addImage(imgData, 'PNG', 0, position, imgW, imgH);
                    heightLeft -= pageHeight;

                    // Subsequent pages if content overflows
                    while (heightLeft > 0) {
                        position = heightLeft - imgH;
                        pdf.addPage();
                        pdf.addImage(imgData, 'PNG', 0, position, imgW, imgH);
                        heightLeft -= pageHeight;
                    }

                    const filename = "Match_Point_Card_Summary_<?php echo str_replace(' ', '_', $userFullName); ?>_<?php echo $year; ?>.pdf";
                    pdf.save(filename);

                    overlay.innerHTML = '<p style="color:#16a34a; font-weight:700;">PDF Downloaded!</p><button onclick="window.close()" style="margin-top:10px; cursor:pointer; padding:8px 16px; background:#1e3a8a; color:#fff; border:none; border-radius:6px;">Close Window</button>';
                }).catch(err => {
                    console.error(err);
                    overlay.innerHTML = '<p style="color:#ef4444; font-weight:700;">Failed to generate PDF.</p><p>' + err.message + '</p>';
                });
            }, 1500);
        };
    </script>
</body>

</html>