<?php
/**
 * Guards - My Profile/Contract
 * View personal profile and download contract
 */

$db = $GLOBALS['db'];

// Verify guard access
$user = $db->fetch("SELECT * FROM users WHERE id = ? AND role = 'guard'", [$_SESSION['user_id'] ?? 0]);
if (!$user) {
    header('Location: ?page=dashboard');
    exit();
}

// Handle contract view
$action = $_GET['action'] ?? null;
if ($action === 'view_contract') {
    $staff = $db->fetch("SELECT * FROM staff WHERE user_id = ?", [$_SESSION['user_id']]);
    if (!$staff) {
        header('Location: ?page=guards&page_action=profile');
        exit();
    }
    
    // Get company settings
    $settings = $db->fetch("SELECT * FROM settings LIMIT 1") ?: [];
    
    // Prepare contract variables
    $contract_date = date('Y-m-d');
    $company_name = $settings['site_name'] ?? 'SHEPHERD SECURITY AND CONSULTANCY INTERNATIONAL';
    $company_address = $settings['company_address'] ?? 'Opposite PCSS Buea Town, P.O.Box 554, Buea';
    $company_email = $settings['company_email'] ?? 'info@ssci.cm';
    $company_phone = $settings['company_phone'] ?? 'Tel: (237) 676037526';
    $employee_name = $user['name'];
    
    // Include contract template
    require SSCI_VIEWS . '/components/staff_contract.php';
    exit();
}

// Handle badge view
if ($action === 'view_badge') {
    $staff = $db->fetch("SELECT * FROM staff WHERE user_id = ?", [$_SESSION['user_id']]);
    if (!$staff) {
        header('Location: ?page=guards&page_action=profile');
        exit();
    }
    
    // Generate QR code
    $qr_data = "Guard-{$staff['badge_number']}-{$user['name']}";
    $qr_url = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' . urlencode($qr_data);
    $employee_name = $user['name'];
    
    // Include badge template
    require SSCI_VIEWS . '/components/staff_badge.php';
    exit();
}

// Get staff/contract information
$staff = $db->fetch("SELECT * FROM staff WHERE user_id = ?", [$_SESSION['user_id']]);

// Get latest salary information for download
$salary = $db->fetch(
    "SELECT id FROM staff_salaries WHERE staff_id = ? ORDER BY created_at DESC LIMIT 1",
    [$_SESSION['user_id']]
);

// Get assignment information
$assignment = $db->fetch(
    "SELECT gpa.*, p.name as post_name, p.location, p.facility_type
     FROM guard_post_assignments gpa
     JOIN posts p ON gpa.post_id = p.id
     WHERE gpa.guard_id = ? AND gpa.status = 'Active'",
    [$_SESSION['user_id']]
);

require_once __DIR__ . '/../../layouts/header.php';
?>

<div class="container mx-auto px-4 py-8 max-w-5xl">
    <!-- Header -->
    <div class="mb-8">
        <div class="bg-gradient-to-r from-green-600 to-green-700 rounded-lg p-8 text-white shadow-lg">
            <div class="flex items-center gap-6">
                <div class="w-24 h-24 bg-white rounded-full flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-user text-4xl text-green-600"></i>
                </div>
                <div>
                    <h1 class="text-4xl font-bold"><?php echo htmlspecialchars($user['name']); ?></h1>
                    <p class="text-green-100 mt-2 text-lg">
                        <i class="fas fa-shield-alt mr-2"></i>Security Guard
                    </p>
                </div>
            </div>
        </div>
    </div>

    <!-- Two Column Layout -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- Left Column - Profile Info -->
        <div class="lg:col-span-2 space-y-6">
            <!-- Personal Information Card -->
            <div class="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden">
                <div class="bg-gradient-to-r from-green-50 to-green-100 border-b border-gray-200 px-6 py-4">
                    <h2 class="text-2xl font-bold text-gray-900">
                        <i class="fas fa-user-circle text-green-600 mr-3"></i>Personal Information
                    </h2>
                </div>
                
                <div class="p-8 space-y-5">
                    <div class="grid grid-cols-2 gap-6">
                        <!-- Email -->
                        <div>
                            <label class="text-xs font-bold text-gray-600 uppercase tracking-wide block mb-2">Email Address</label>
                            <p class="text-gray-800 font-semibold text-lg break-all"><?php echo htmlspecialchars($user['email']); ?></p>
                        </div>

                        <!-- Phone -->
                        <div>
                            <label class="text-xs font-bold text-gray-600 uppercase tracking-wide block mb-2">Phone Number</label>
                            <p class="text-gray-800 font-semibold text-lg"><?php echo htmlspecialchars($user['phone'] ?? 'Not provided'); ?></p>
                        </div>

                        <!-- Role -->
                        <div>
                            <label class="text-xs font-bold text-gray-600 uppercase tracking-wide block mb-2">Role</label>
                            <span class="inline-block px-4 py-2 bg-green-100 text-green-900 rounded-full font-bold">
                                <i class="fas fa-badge mr-2"></i>Guard
                            </span>
                        </div>

                        <!-- Account Status -->
                        <div>
                            <label class="text-xs font-bold text-gray-600 uppercase tracking-wide block mb-2">Account Status</label>
                            <span class="inline-block px-4 py-2 <?php echo $user['active'] ? 'bg-green-100 text-green-900' : 'bg-red-100 text-red-900'; ?> rounded-full font-bold">
                                <i class="fas <?php echo $user['active'] ? 'fa-check-circle' : 'fa-times-circle'; ?> mr-2"></i>
                                <?php echo $user['active'] ? 'Active' : 'Inactive'; ?>
                            </span>
                        </div>
                    </div>

                    <!-- Address (if available from staff table) -->
                    <?php if ($staff && !empty($staff['address'])): ?>
                        <div class="border-t border-gray-200 pt-6">
                            <label class="text-xs font-bold text-gray-600 uppercase tracking-wide block mb-2">Residential Address</label>
                            <p class="text-gray-800 font-semibold leading-relaxed"><?php echo htmlspecialchars($staff['address']); ?></p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Current Assignment Card -->
            <?php if ($assignment): ?>
                <div class="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden">
                    <div class="bg-gradient-to-r from-blue-50 to-blue-100 border-b border-gray-200 px-6 py-4">
                        <h2 class="text-2xl font-bold text-gray-900">
                            <i class="fas fa-map-pin text-blue-600 mr-3"></i>Current Assignment
                        </h2>
                    </div>
                    
                    <div class="p-8 space-y-5">
                        <!-- Post Name -->
                        <div>
                            <label class="text-xs font-bold text-gray-600 uppercase tracking-wide block mb-2">Assigned Post</label>
                            <p class="text-2xl font-bold text-gray-800"><?php echo htmlspecialchars($assignment['post_name']); ?></p>
                        </div>

                        <div class="grid grid-cols-2 gap-6">
                            <!-- Facility Type -->
                            <div>
                                <label class="text-xs font-bold text-gray-600 uppercase tracking-wide block mb-2">Facility Type</label>
                                <p class="text-gray-800 font-semibold"><?php echo htmlspecialchars($assignment['facility_type'] ?? 'N/A'); ?></p>
                            </div>

                            <!-- Assigned Hours -->
                            <div>
                                <label class="text-xs font-bold text-gray-600 uppercase tracking-wide block mb-2">Weekly Hours</label>
                                <p class="text-gray-800 font-semibold"><?php echo htmlspecialchars($assignment['created_at'] ?? 'N/A'); ?></p>
                            </div>
                        </div>

                        <!-- Location -->
                        <div>
                            <label class="text-xs font-bold text-gray-600 uppercase tracking-wide block mb-2">Location</label>
                            <p class="text-gray-800 font-semibold flex items-center gap-2">
                                <i class="fas fa-location-dot text-blue-500"></i>
                                <?php echo htmlspecialchars($assignment['location'] ?? 'Not specified'); ?>
                            </p>
                        </div>

                        <!-- Assignment Status -->
                        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                            <p class="text-xs font-bold text-blue-700 uppercase mb-2">Assignment Status</p>
                            <p class="text-blue-900 font-semibold">
                                <i class="fas fa-check-circle mr-2"></i>
                                Active since <?php echo date('M d, Y', strtotime($assignment['created_at'] ?? date('Y-m-d'))); ?>
                            </p>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Staff/Badge Information -->
            <?php if ($staff): ?>
                <div class="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden">
                    <div class="bg-gradient-to-r from-purple-50 to-purple-100 border-b border-gray-200 px-6 py-4">
                        <h2 class="text-2xl font-bold text-gray-900">
                            <i class="fas fa-id-badge text-purple-600 mr-3"></i>Staff Badge Information
                        </h2>
                    </div>
                    
                    <div class="p-8 space-y-5">
                        <div class="grid grid-cols-2 gap-6">
                            <!-- Badge Number -->
                            <div>
                                <label class="text-xs font-bold text-gray-600 uppercase tracking-wide block mb-2">Badge Number</label>
                                <p class="text-2xl font-bold text-purple-600 font-mono"><?php echo htmlspecialchars($staff['badge_number'] ?? 'N/A'); ?></p>
                            </div>

                            <!-- Department -->
                            <div>
                                <label class="text-xs font-bold text-gray-600 uppercase tracking-wide block mb-2">Department</label>
                                <p class="text-gray-800 font-semibold"><?php echo htmlspecialchars($staff['department'] ?? 'Security'); ?></p>
                            </div>

                            <!-- Hire Date -->
                            <div>
                                <label class="text-xs font-bold text-gray-600 uppercase tracking-wide block mb-2">Hire Date</label>
                                <p class="text-gray-800 font-semibold"><?php echo (!empty($staff['hire_date']) ? date('M d, Y', strtotime($staff['hire_date'])) : 'N/A'); ?></p>
                            </div>

                            <!-- Employment Type -->
                            <div>
                                <label class="text-xs font-bold text-gray-600 uppercase tracking-wide block mb-2">Employment Type</label>
                                <p class="text-gray-800 font-semibold"><?php echo htmlspecialchars($staff['employment_type'] ?? 'Full-time'); ?></p>
                            </div>
                        </div>

                        <!-- Emergency Contact -->
                        <?php if (!empty($staff['emergency_contact'])): ?>
                            <div class="border-t border-gray-200 pt-6">
                                <label class="text-xs font-bold text-gray-600 uppercase tracking-wide block mb-2">Emergency Contact</label>
                                <p class="text-gray-800 font-semibold"><?php echo htmlspecialchars($staff['emergency_contact']); ?></p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- Right Column - Actions -->
        <div class="lg:col-span-1">
            <!-- Quick Actions -->
            <div class="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden sticky top-20">
                <div class="bg-gradient-to-r from-green-50 to-green-100 border-b border-gray-200 px-6 py-4">
                    <h3 class="text-xl font-bold text-gray-900">
                        <i class="fas fa-lightning-bolt text-green-600 mr-2"></i>Quick Actions
                    </h3>
                </div>

                <div class="p-6 space-y-3">
                    <!-- Download Payslip -->
                    <?php if ($salary): ?>
                        <button onclick="downloadPayslip(<?php echo $salary['id']; ?>)" class="w-full px-4 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition font-bold flex items-center justify-center gap-2" title="Download payslip as PDF">
                            <i class="fas fa-file-invoice-dollar"></i>
                            <span>Download Payslip</span>
                        </button>
                    <?php else: ?>
                        <button disabled class="w-full px-4 py-3 bg-gray-400 text-white rounded-lg cursor-not-allowed font-bold flex items-center justify-center gap-2" title="No salary record found">
                            <i class="fas fa-file-invoice-dollar"></i>
                            <span>No Payslip Available</span>
                        </button>
                    <?php endif; ?>

                    <!-- Download Contract -->
                    <button onclick="downloadContract()" class="w-full px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition font-bold flex items-center justify-center gap-2" title="Download contract as PDF">
                        <i class="fas fa-file-pdf"></i>
                        <span>Download Contract</span>
                    </button>

                    <!-- Download Badge -->
                    <button onclick="downloadBadge()" class="w-full px-4 py-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition font-bold flex items-center justify-center gap-2" title="Download badge as image">
                        <i class="fas fa-id-badge"></i>
                        <span>Download Badge</span>
                    </button>

                    <hr class="my-2">

                    <!-- View Patrols -->
                    <a href="?page=guards-patrols" class="w-full px-4 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition font-bold flex items-center justify-center gap-2">
                        <i class="fas fa-shoe-prints"></i>
                        <span>View Patrols</span>
                    </a>

                    <!-- View Controls -->
                    <a href="?page=guards-controls" class="w-full px-4 py-3 bg-cyan-600 text-white rounded-lg hover:bg-cyan-700 transition font-bold flex items-center justify-center gap-2">
                        <i class="fas fa-clipboard-check"></i>
                        <span>View Controls</span>
                    </a>

                    <!-- View Payments -->
                    <a href="?page=guards-payments" class="w-full px-4 py-3 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition font-bold flex items-center justify-center gap-2">
                        <i class="fas fa-money-bill"></i>
                        <span>View Payments</span>
                    </a>

                    <!-- Send Message -->
                    <a href="?page=guards-messages" class="w-full px-4 py-3 bg-rose-600 text-white rounded-lg hover:bg-rose-700 transition font-bold flex items-center justify-center gap-2">
                        <i class="fas fa-envelope"></i>
                        <span>Send Message</span>
                    </a>
                </div>
            </div>

            <!-- Profile Stats -->
            <div class="mt-8 space-y-4">
                <!-- Assignment Duration -->
                <?php if ($assignment && !empty($assignment['assigned_date'])): 
                    $assignedDate = new DateTime($assignment['assigned_date']);
                    $today = new DateTime();
                    $duration = $today->diff($assignedDate);
                ?>
                    <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl border-2 border-blue-200 p-6 text-center">
                        <p class="text-3xl font-bold text-blue-900"><?php echo $duration->y; ?></p>
                        <p class="text-sm font-semibold text-blue-700 mt-1">Years in Service</p>
                        <p class="text-xs text-blue-600 mt-3">Since <?php echo date('M d, Y', strtotime($assignment['assigned_date'])); ?></p>
                    </div>
                <?php endif; ?>

                <!-- Help Card -->
                <div class="bg-gradient-to-br from-green-50 to-green-100 rounded-xl border-2 border-green-200 p-6">
                    <p class="text-sm font-semibold text-green-900 mb-4">
                        <i class="fas fa-question-circle mr-2"></i>Need Help?
                    </p>
                    <p class="text-xs text-green-800 leading-relaxed">
                        Contact the administration office for profile updates or contract inquiries.
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
/**
 * Download Payslip as PDF
 */
function downloadPayslip(salaryId) {
    if (!salaryId) {
        Swal.fire({
            title: 'No Salary Record',
            text: 'No salary record found to download.',
            icon: 'warning',
            confirmButtonText: 'OK',
            confirmButtonColor: '#16a34a'
        });
        return;
    }

    const link = document.createElement('a');
    link.href = `?page=api&endpoint=guards/payslip&id=${salaryId}`;
    link.download = `Payslip_${new Date().getTime()}.pdf`;
    
    Swal.fire({
        title: 'Downloading Payslip...',
        html: 'Please wait while we prepare your payslip PDF.',
        icon: 'info',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
            setTimeout(() => {
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                Swal.close();
            }, 1000);
        }
    });
}

/**
 * Download Contract as PDF
 */
function downloadContract() {
    const link = document.createElement('a');
    link.href = `?page=api&endpoint=guards/contract-pdf`;
    link.download = `Contract_${new Date().getTime()}.pdf`;
    
    Swal.fire({
        title: 'Downloading Contract...',
        html: 'Please wait while we prepare your employment contract PDF.',
        icon: 'info',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
            setTimeout(() => {
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                Swal.close();
            }, 1000);
        }
    });
}

/**
 * Download Badge as Image
 */
function downloadBadge() {
    const link = document.createElement('a');
    link.href = `?page=api&endpoint=guards/badge-image`;
    link.target = '_blank';
    
    Swal.fire({
        title: 'Opening Badge Editor...',
        html: 'A new window will open with your badge. You can download it as a high-resolution PNG image.',
        icon: 'info',
        confirmButtonText: 'Open Badge',
        confirmButtonColor: '#4f46e5',
        allowOutsideClick: false
    }).then((result) => {
        if (result.isConfirmed) {
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    });
}
</script>

<?php require_once __DIR__ . '/../../layouts/footer.php'; ?>
