<?php
/**
 * CCAC CTPL Online - Optimized for Speed & Split Names
 */
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$message_sent = false;
$error = "";

$rates = ["PC1" => 786.00, "PC2" => 836.00, "CV1" => 836.00, "CV2" => 910.00];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $firstName  = htmlspecialchars($_POST['first_name']);
    $middleName = htmlspecialchars($_POST['middle_name']);
    $lastName   = htmlspecialchars($_POST['last_name']);
    $fullName   = trim("$firstName $middleName $lastName");
    $contactNo  = htmlspecialchars($_POST['contact_no']);
    $email      = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    $unitType   = $_POST['unit_type'];
    $selectedPremium = isset($rates[$unitType]) ? number_format($rates[$unitType], 2) : "786.00";
    
    if (isset($_FILES['attachments']) && !empty($_FILES['attachments']['name'][0])) {
        $mail = new PHPMailer(true);
        try {
            // SMTP Settings
            $mail->isSMTP();
            $mail->Host       = 'smtp.gmail.com'; 
            $mail->SMTPAuth   = true;
            $mail->Username   = 'jad.cruiserscrib@gmail.com';
            $mail->Password   = 'algd pmnj rwak rauf'; 
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = 587;
            $mail->SMTPKeepAlive = true;

            // EMAIL 1: To Admin
            $mail->setFrom('system@cruiserscrib.com', 'Cruisers Crib AutoCare');
            $mail->addAddress('jad.cruiserscrib@gmail.com');
            $mail->addReplyTo($email, $fullName);

            foreach ($_FILES['attachments']['tmp_name'] as $key => $tmpName) {
                if ($_FILES['attachments']['error'][$key] == UPLOAD_ERR_OK) {
                    $mail->addAttachment($tmpName, $_FILES['attachments']['name'][$key]);
                }
            }

            $mail->isHTML(true);
            $mail->Subject = "CTPL Application - $fullName";
            $mail->Body    = "
                <div style='font-family: Arial; border-top: 5px solid #f97316; padding: 20px;'>
                    <h2>New CTPL Request Received</h2><hr>
                    <p><strong>Name:</strong> $fullName</p>
                    <p><strong>Contact:</strong> $contactNo</p>
                    <p><strong>Email:</strong> $email</p>
                    <p><strong>Unit:</strong> $unitType</p>
                    <p><strong>Premium:</strong> ₱ $selectedPremium</p>
                    <p><strong>Privacy Consent:</strong> Agreed</p>
                </div>";
            $mail->send();

            // EMAIL 2: To Client
            $mail->clearAddresses();
            $mail->clearAttachments();
            $mail->addAddress($email);
            $mail->Subject = "Application Received: CTPL Insurance for $firstName";
            $mail->Body    = "
                <div style='font-family: Arial, sans-serif; border-top: 5px solid #f97316; padding: 20px; color: #333;'>
                    <p>Dear $firstName,</p>
                    <p>Good day!</p>
                    <p>Thank you for choosing <strong>Cruisers Crib Auto Care</strong>. We have successfully received your application for CTPL Insurance.</p>
                    <p>To finalize your policy, please take note of the following:</p>
                    <p><strong>Timeframe:</strong> One of our Marketing Specialists will call you within the next 24 hours (one business day).<br>
                    <strong>Our Number:</strong> Please keep your line open for a call from <b>0927 370 4947</b>.<br>
                    <strong>Preparation:</strong> To speed up the process, please have a digital copy or clear photo of your OR/CR (Official Receipt and Certificate of Registration) ready.</p>
                    <p>We look forward to assisting you with your registration!</p>
                    <p>Best regards,</p>
                    <br>
                    <p><strong>The Cruisers Crib Team</strong></p>
                    <p style='font-size: 12px; color: #999;'><hr>This is an automated message.</p>
                </div>";
            $mail->send();
            
            $mail->getSMTPInstance()->reset(); 
            $message_sent = true;
        } catch (Exception $e) { $error = "System Error: {$mail->ErrorInfo}"; }
    } else { $error = "Upload required: Attach Receipt and ORCR."; }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get CTPL Online | Cruisers Crib</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700;900&display=swap');
        body { font-family: 'Inter', sans-serif; }
        
        #loading-overlay {
            display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.8);
            z-index: 10000; flex-direction: column; align-items: center; justify-content: center;
        }

        .messenger-static {
            position: fixed; bottom: 25px; right: 25px; width: 60px; height: 60px;
            background: linear-gradient(135deg, #00B2FF, #006AFF);
            border-radius: 50%; display: flex; align-items: center; justify-content: center;
            color: white; font-size: 30px; box-shadow: 0 10px 25px rgba(0, 106, 255, 0.4);
            z-index: 9999; text-decoration: none;
        }

        .pulse-anim { animation: shadow-pulse 2s infinite; }
        @keyframes shadow-pulse {
            0% { box-shadow: 0 0 0 0 rgba(0, 132, 255, 0.7); }
            70% { box-shadow: 0 0 0 15px rgba(0, 132, 255, 0); }
            100% { box-shadow: 0 0 0 0 rgba(0, 132, 255, 0); }
        }
        
        .step-circle { 
            width: 32px; height: 32px; display: flex; align-items: center; justify-content: center;
            border-radius: 9999px; background-color: #f87718; color: #000;
            font-weight: 900; font-size: 0.875rem; margin-right: 0.75rem;
        }

        @keyframes flip-extreme {
            0% { transform: rotateY(0deg); }
            50% { transform: rotateY(180deg); }
            100% { transform: rotateY(0deg); }
        }
        .animate-flip { animation: flip-extreme 4s ease-in-out infinite; }
    </style>
</head>
<body class="bg-[#f87718] min-h-screen py-10 px-4">

    <div id="loading-overlay">
        <div class="animate-spin text-[#f87718] text-6xl mb-4"><i class="fa-solid fa-circle-notch"></i></div>
        <p class="text-white font-black uppercase tracking-widest italic">Processing Application...</p>
        <p class="text-gray-400 text-[10px] mt-2">Uploading documents and sending confirmation.</p>
    </div>

    <a href="https://m.me/cruisers.crib.autocare" target="_blank" class="messenger-static pulse-anim">
        <i class="fa-brands fa-facebook-messenger"></i>
    </a>

    <div class="max-w-xl mx-auto">
        <div class="flex flex-col items-center mb-8">
            <img src="images/CCAC_Logo.png" alt="CCAC Logo" class="h-32 md:h-40 mb-6 object-contain animate-flip">
            <div class="w-full max-w-[90%] md:max-w-md bg-black py-4 rounded-[2rem] border-b-8 border-[#111] shadow-2xl flex justify-center items-center px-4">
                <p class="font-black text-[12px] md:text-[16px] uppercase tracking-[0.2em] text-white italic text-center">Online CTPL Portal</p>
            </div>
        </div>

        <div class="bg-white rounded-[2rem] shadow-2xl overflow-hidden border-b-8 border-black">
            <div class="bg-black p-3 text-center text-white font-bold flex justify-center items-center text-[10px] uppercase tracking-widest">
                <span class="text-[#f87718] mr-2">●</span> Fast Issuance <span class="mx-3 text-gray-700">|</span> <span class="text-[#f87718] mr-2">●</span> LTO Authenticated
            </div>

            <div class="p-6 md:p-10">
                <?php if ($message_sent): ?>
                    <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-6 rounded-r-xl font-bold italic flex flex-col md:flex-row items-center justify-between">
                        <span>Application Sent! Check your email.</span>
                        <a href="?" class="mt-2 md:mt-0 text-[10px] bg-green-500 text-white px-3 py-1 rounded-full uppercase not-italic hover:bg-black transition-colors">
                            <i class="fa-solid fa-rotate-right mr-1"></i> New Application
                        </a>
                    </div>
                <?php endif; ?>

                <?php if ($error): ?>
                    <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded-r-xl font-bold italic"><?= $error ?></div>
                <?php endif; ?>

                <form id="ctplForm" action="" method="POST" enctype="multipart/form-data" class="space-y-8">
                    <div>
                        <div class="flex items-center mb-6"><div class="step-circle">1</div><h3 class="font-black text-black uppercase tracking-tight text-xs md:text-sm">Personal Details</h3></div>
                        <div class="space-y-4">
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <input type="text" name="first_name" placeholder="First Name" required class="w-full border-2 border-gray-100 p-4 rounded-2xl focus:border-[#f87718] outline-none font-semibold text-gray-800 bg-gray-50/50">
                                <input type="text" name="middle_name" placeholder="Middle Name" class="w-full border-2 border-gray-100 p-4 rounded-2xl focus:border-[#f87718] outline-none font-semibold text-gray-800 bg-gray-50/50">
                                <input type="text" name="last_name" placeholder="Last Name" required class="w-full border-2 border-gray-100 p-4 rounded-2xl focus:border-[#f87718] outline-none font-semibold text-gray-800 bg-gray-50/50">
                            </div>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <input type="text" name="contact_no" placeholder="Contact No." required class="border-2 border-gray-100 p-4 rounded-2xl focus:border-[#f87718] outline-none font-semibold text-gray-800 bg-gray-50/50">
                                <input type="email" name="email" placeholder="Email Address" required class="border-2 border-gray-100 p-4 rounded-2xl focus:border-[#f87718] outline-none font-semibold text-gray-800 bg-gray-50/50">
                            </div>
                        </div>
                    </div>

                    <div>
                        <div class="flex items-center mb-6"><div class="step-circle">2</div><h3 class="font-black text-black uppercase tracking-tight text-xs md:text-sm">Unit Type</h3></div>
                        <select name="unit_type" id="unit_type" onchange="updatePremium()" class="w-full border-2 border-gray-100 p-4 rounded-2xl bg-gray-50 font-black text-black focus:border-[#f87718] outline-none cursor-pointer">
                            <option value="PC1">PC1 (Sedan, Hatchback)</option>
                            <option value="PC2">PC2 (Crossover, MPV, SUV, Pick-up)</option>
                            <option value="CV1">CV1 (FB Body, 4 Wheeler)</option>
                            <option value="CV2">CV2 (6 Wheeler, Medium Truck)</option>
                        </select>
                        <div class="mt-6 bg-[#111] p-6 rounded-3xl text-center border-b-4 border-[#f87718]">
                            <span class="text-[9px] font-black text-[#f87718] uppercase tracking-[0.3em] block mb-2">Total Premium Due</span>
                            <span class="text-4xl font-black text-white italic">₱<span id="display_premium">786</span><span class="text-sm font-normal text-gray-500 not-italic ml-1">.00</span></span>
                        </div>
                    </div>

                    <div>
                        <div class="flex items-center mb-6"><div class="step-circle">3</div><h3 class="font-black text-black uppercase tracking-tight text-xs md:text-sm">Payment</h3></div>
                        <div class="rounded-3xl border-2 border-gray-100 overflow-hidden mb-6 shadow-md"><img src="images/GCash-BDO-RCBC.jpg" class="w-full"></div>
                        
                        <button type="button" onclick="contactSupport()" class="w-full flex items-center justify-center bg-[#006AFF] hover:bg-black text-white px-8 py-5 rounded-2xl text-[10px] md:text-[11px] font-black uppercase tracking-widest shadow-xl active:scale-95 transition-all">
                            <i class="fa-brands fa-facebook-messenger mr-3 text-lg"></i> Chat With Us for Payment Details
                        </button>
                    </div>

                    <div>
                        <div class="flex items-center mb-6"><div class="step-circle">4</div><h3 class="font-black text-black uppercase tracking-tight text-xs md:text-sm">Submission</h3></div>
                        <div class="relative border-2 border-gray-100 p-8 rounded-3xl hover:border-[#f87718] transition group bg-gray-50/50 text-center">
                            <input type="file" name="attachments[]" id="file_input" multiple required class="absolute inset-0 w-full h-full opacity-0 z-10 cursor-pointer">
                            <div class="w-16 h-16 bg-orange-100 rounded-full flex items-center justify-center mx-auto mb-4 group-hover:bg-[#f87718] transition-colors"><i class="fa-solid fa-cloud-arrow-up text-3xl text-[#f87718] group-hover:text-black"></i></div>
                            <p class="text-[10px] md:text-[12px] font-black text-black uppercase tracking-tight" id="upload_label">Attach Receipt & ORCR</p>
                        </div>
                        <div id="file_list" class="mt-4 space-y-2 hidden"></div>
                    </div>

                    <div>
                        <div class="flex items-center mb-6"><div class="step-circle">5</div><h3 class="font-black text-black uppercase tracking-tight text-xs md:text-sm">Consent</h3></div>
                        <div class="bg-gray-50 p-6 rounded-3xl border-2 border-gray-100 flex items-start gap-4">
                            <div class="flex items-center h-5">
                                <input id="consent" name="consent" type="checkbox" required class="w-5 h-5 text-[#f87718] border-gray-300 rounded focus:ring-[#f87718] cursor-pointer">
                            </div>
                            <div class="text-[10px] md:text-[11px] text-gray-600 leading-relaxed font-semibold">
                                I hereby give my consent to <span class="text-black font-black uppercase">Cruisers Crib Auto Care Center</span> to collect, process, and use my personal information for the purpose of processing my CTPL Insurance application in accordance with the <strong>Data Privacy Act of 2012</strong>.
                            </div>
                        </div>
                    </div>

                    <button type="submit" class="w-full bg-[#f87718] hover:bg-black hover:text-[#f87718] text-black font-black py-5 rounded-2xl shadow-2xl transition-all uppercase tracking-[0.2em] text-xs md:text-sm italic">
                        Process Application <i class="fa-solid fa-chevron-right ml-3 text-[10px]"></i>
                    </button>
                </form>
            </div>
        </div>
        <p class="text-center text-gray-600 text-[9px] mt-10 font-bold uppercase tracking-[0.5em]">Bacoor • Cavite • PH</p>
    </div>

    <script>
        let attachedFiles = [];
        const form = document.getElementById('ctplForm');
        const loader = document.getElementById('loading-overlay');

        form.onsubmit = function() {
            loader.style.display = 'flex';
        };

        function contactSupport() {
            window.open("https://m.me/cruisers.crib.autocare", "_blank");
        }

        function updatePremium() {
            const select = document.getElementById('unit_type');
            const display = document.getElementById('display_premium');
            const rates = { 'PC1': '786', 'PC2': '836', 'CV1': '836', 'CV2': '910' };
            display.innerText = rates[select.value];
        }

        const fileInput = document.getElementById('file_input');
        const fileListDisplay = document.getElementById('file_list');
        const uploadLabel = document.getElementById('upload_label');

        fileInput.addEventListener('change', function(e) {
            const newFiles = Array.from(this.files);
            attachedFiles = attachedFiles.concat(newFiles);
            this.value = '';
            updateFileList();
        });

        function updateFileList() {
            fileListDisplay.innerHTML = '';
            if (attachedFiles.length > 0) {
                fileListDisplay.classList.remove('hidden');
                uploadLabel.innerText = "Add Another File";
                attachedFiles.forEach((file, index) => {
                    const div = document.createElement('div');
                    div.className = 'text-[10px] bg-white border-2 border-orange-100 rounded-xl p-3 flex items-center justify-between font-black text-black';
                    div.innerHTML = `<span class="truncate pr-4"><i class="fa-solid fa-file-circle-check text-[#f87718] mr-2"></i> ${file.name}</span>
                        <button type="button" onclick="removeFile(event, ${index})" class="text-red-500 px-2"><i class="fa-solid fa-trash-can"></i></button>`;
                    fileListDisplay.appendChild(div);
                });
            } else {
                fileListDisplay.classList.add('hidden');
                uploadLabel.innerText = "Attach Receipt & ORCR";
            }
            const dataTransfer = new DataTransfer();
            attachedFiles.forEach(file => dataTransfer.items.add(file));
            fileInput.files = dataTransfer.files;
        }

        function removeFile(event, index) {
            event.preventDefault();
            attachedFiles.splice(index, 1);
            updateFileList();
        }
    </script>
</body>
</html>