<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
session_write_close();
require '../config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

// 1. Fetch System & Card Layout Settings from Database
$settings_query = "SELECT * FROM id_card_settings LIMIT 1";
$settings_res = $conn->query($settings_query);
$settings = ($settings_res && $settings_res->num_rows > 0) ? $settings_res->fetch_assoc() : [];

$company_name       = (string)($settings['company_name']       ?? 'Best Western Plus Yenagoa');
$company_logo       = !empty($settings['company_logo']) ? (string)$settings['company_logo'] : '../assets/logo.png';
$contact_dept       = (string)($settings['contact_dept']       ?? 'Human Resources Department');
$contact_phone      = (string)($settings['contact_phone']      ?? '+234 800 123 4567');
$contact_email      = (string)($settings['contact_email']      ?? 'hr@bwpyenagoa.com');
$signature_title    = (string)($settings['signature_title']    ?? 'Authorised Signatory');
$card_footer_text   = (string)($settings['footer_text']        ?? 'Property of management. Return upon request.');

// Selected dynamic template (Defaults to template_1)
$selected_template = (string)($settings['template_style'] ?? 'template_1');

// 2. Fetch Card & Employee Details
$card_id = (int)($_GET['id'] ?? 0);

$sql = "SELECT c.*, e.employee_no, e.name, e.designation, e.phone, e.email, e.avatar, d.name AS department_name
        FROM id_cards c
        JOIN employees e ON e.id = c.employee_id
        LEFT JOIN departments d ON (d.id = e.department_id OR d.name = e.department_id)
        WHERE c.id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $card_id);
$stmt->execute();
$card = $stmt->get_result()->fetch_assoc();

if (!$card) {
    echo "Record not found.";
    exit;
}

// 3. Resolve Dynamic Employee Avatar Image
$rawAvatar = !empty($card['avatar']) ? trim((string)$card['avatar']) : '';
$avatarPhoto = null;

if (!empty($rawAvatar)) {
    $cleanPath = ltrim(str_replace('\\', '/', $rawAvatar), './');
    $serverPath = __DIR__ . '/../' . $cleanPath;
    if (file_exists($serverPath)) {
        $avatarPhoto = '../' . htmlspecialchars($cleanPath);
    }
}

// Resolve Authorised Signature Image
$rawSignature = !empty($settings['authorised_signature']) ? trim((string)$settings['authorised_signature']) : '';
$signaturePhoto = null;

if (!empty($rawSignature)) {
    $cleanSigPath = ltrim(str_replace('\\', '/', $rawSignature), './');
    $serverSigPath = __DIR__ . '/../' . $cleanSigPath;
    if (file_exists($serverSigPath)) {
        $signaturePhoto = '../' . htmlspecialchars($cleanSigPath);
    }
}

// Generate Name Initials as Fallback
$cleanName = !empty($card['name']) ? htmlspecialchars((string)$card['name']) : 'Unnamed Staff';
$cleanStr  = preg_replace('/^(mr\.|ms\.|mrs\.|dr\.|prof\.)\s+/i', '', trim($cleanName));
$words     = explode(' ', $cleanStr);
$initials  = strtoupper(substr(($words[0] ?? '') . ($words[1] ?? ''), 0, 2));
if (empty($initials)) $initials = 'EE';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Print ID Card - <?= htmlspecialchars((string)($card['employee_no'] ?? 'N/A')); ?></title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Mulish:ital,wght=0,200..1000;1,200..1000&display=swap" rel="stylesheet">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        brandPrimary: '#8B1936',
                        brandSecondary: '#595660'
                    },
                    fontFamily: {
                        sans: ['Mulish', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <link rel="stylesheet" href="../components/sidebar.css">

    <style>
        @page {
            size: A4 portrait;
            margin: 0;
        }
        @media print {
            body { 
                background: white !important; 
                padding: 0 !important;
            }
            #sidebar-wrapper,
            #sidebar-overlay,
            .no-print { 
                display: none !important; 
            }
            #main-content {
                padding-left: 0 !important;
            }
            .cr80-card {
                box-shadow: none !important;
                border: 1px solid #ccc !important;
            }
        }

        .cr80-card {
            width: 2.125in;
            height: 3.375in;
            box-sizing: border-box;
        }
    </style>
</head>
<body class="bg-stone-100/60 min-h-screen text-slate-800 antialiased font-sans">

    <div class="flex">
        
        <?php include '../components/sidebar.php'; ?>

        <div id="sidebar-overlay" class="fixed inset-0 bg-slate-900/40 hidden z-40 transition-opacity duration-300" onclick="toggleSidebar()"></div>

        <div id="main-content" class="flex-1 min-w-0 md:pl-60 transition-all duration-300 min-h-screen flex flex-col">
            
            <!-- Header (Hidden on Print) -->
            <header class="no-print sticky top-0 bg-white/90 backdrop-blur-md border-b border-slate-300/80 h-14 flex items-center justify-between px-4 sm:px-6 z-30 shadow-xs">
                <div class="flex items-center gap-3">
                    <button onclick="toggleSidebar()" class="p-1.5 rounded-lg text-slate-600 hover:bg-slate-200/80 transition active:scale-95" aria-label="Toggle Side Area Menu">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16"></path>
                        </svg>
                    </button>
                    <div>
                        <h1 class="text-sm font-black tracking-tight text-slate-950">Print ID Card</h1>
                        <p class="text-[10px] text-[#8B1936] font-bold uppercase tracking-wider">Preview & Production Mode</p>
                    </div>
                </div>
                
                <div class="flex items-center gap-4">
                    <a href="index.php" class="text-xs font-bold text-slate-600 hover:text-slate-900 transition flex items-center gap-1">
                        ← Back to Dashboard
                    </a>
                </div>
            </header>

            <main class="flex-1 p-4 sm:p-6 max-w-4xl w-full mx-auto space-y-6 flex flex-col items-center">

                <!-- Action Control Bar (Hidden on Print) -->
                <div class="no-print w-full flex items-center justify-between bg-white p-4 rounded-xl shadow-xs border border-slate-300/80">
                    <div>
                        <h2 class="text-xs font-black text-slate-950 uppercase tracking-tight">Active ID Card Layout</h2>
                        <p class="text-[10px] text-[#595660] font-semibold mt-0.5">
                            Template: <span class="text-[#8B1936] font-bold uppercase"><?= htmlspecialchars($selected_template); ?></span>
                        </p>
                    </div>
                    <div class="flex items-center gap-3">
                        <a href="settings.php" class="px-3 py-2 bg-stone-100 hover:bg-slate-200 text-slate-700 font-bold text-xs rounded-lg transition">
                            Change Template
                        </a>
                        <button onclick="window.print()" class="px-4 py-2 bg-[#8B1936] hover:opacity-90 text-white font-bold text-xs rounded-lg shadow-sm transition active:scale-95 flex items-center gap-1.5">
                            🖨️ Start Printing
                        </button>
                    </div>
                </div>

                <!-- Cards Printing Container -->
                <div class="flex flex-col sm:flex-row gap-8 items-center justify-center my-auto py-4">

                    <!-- DYNAMIC FRONT OF CARD -->
                    <?php
                        $template_file = __DIR__ . "/templates/{$selected_template}.php";
                        if (file_exists($template_file)) {
                            include $template_file;
                        } else {
                            include __DIR__ . "/templates/template_1.php";
                        }
                    ?>

                    <!-- BACK OF CARD -->
                    <div class="cr80-card bg-white rounded-xl shadow-lg border border-slate-300 flex flex-col justify-between overflow-hidden text-center p-3 relative">
                        
                        <div class="flex flex-col items-center space-y-1 pt-1">
                            <?php if (file_exists($company_logo) || filter_var($company_logo, FILTER_VALIDATE_URL)): ?>
                                <div class="bg-white p-1 rounded-md flex items-center justify-center">
                                    <img src="<?= htmlspecialchars($company_logo); ?>" alt="Company Logo" class="h-7 max-w-[1.7in] object-contain">
                                </div>
                            <?php else: ?>
                                <h3 class="text-[9.5px] font-black text-[#8B1936] tracking-tight">
                                    <?= htmlspecialchars(ucwords(strtolower($company_name))); ?>
                                </h3>
                            <?php endif; ?>
                            <div class="w-8 h-0.5 bg-[#8B1936] mx-auto rounded-full"></div>
                        </div>

                        <div class="space-y-1.5 text-[7.5px] text-[#595660] font-semibold">
                            <p class="leading-tight">
                                This identification card remains the property of <?= htmlspecialchars(ucwords(strtolower($company_name))); ?>.
                            </p>
                            
                            <div class="bg-stone-50 border border-slate-200 p-1.5 rounded text-left space-y-0.5">
                                <p class="font-bold text-[#8B1936] text-[7px]">If found, please return to:</p>
                                <p class="font-extrabold text-slate-800 text-[7.5px]">
                                    <?= htmlspecialchars(ucwords(strtolower($contact_dept))); ?>
                                </p>
                                <p class="truncate">Phone: <?= htmlspecialchars($contact_phone); ?></p>
                                <p class="truncate">Email: <?= htmlspecialchars($contact_email); ?></p>
                            </div>
                        </div>

                        <!-- Authorised Signature Area -->
                        <div class="flex flex-col items-center justify-center space-y-0.5 my-1">
                            <?php if ($signaturePhoto): ?>
                                <img src="<?= $signaturePhoto; ?>" alt="Authorised Signature" class="h-8 max-w-[1.4in] object-contain">
                            <?php else: ?>
                                <div class="w-28 border-b border-dashed border-slate-400 h-6 flex items-end justify-center">
                                    <span class="text-[6.5px] text-slate-400 font-mono italic">Sign Here</span>
                                </div>
                            <?php endif; ?>
                            <p class="text-[7px] font-extrabold uppercase text-slate-800 tracking-wider">
                                <?= htmlspecialchars($signature_title); ?>
                            </p>
                        </div>

                        <!-- Card Footer Text & Card Number -->
                        <div class="flex flex-col items-center space-y-0.5 pt-1 border-t border-slate-200">
                            <p class="text-[6.5px] text-slate-500 font-bold uppercase tracking-tight line-clamp-1">
                                <?= htmlspecialchars($card_footer_text); ?>
                            </p>
                            <p class="text-[7.5px] font-mono font-bold text-[#8B1936]">
                                Card No: <?= htmlspecialchars((string)($card['card_number'] ?? 'N/A')); ?>
                            </p>
                        </div>

                        <div class="h-1 bg-[#8B1936] w-full -mx-3 -mb-3"></div>
                    </div>

                </div>

            </main>

            <!-- Footer (Hidden on Print) -->
            <footer class="no-print mt-auto border-t border-slate-300 bg-white px-6 py-4 text-center">
                <p class="text-[9px] text-[#595660] font-mono tracking-wider">&copy; <?= date('Y'); ?> Core HR Engine System Platform • Dynamic Secure Architecture Protocol.</p>
            </footer>
        </div>
    </div>

    <script src="../components/sidebar.js"></script>
    <?php include '../loader_overlay.php'; ?>
</body>
</html>