<?php
/**
 * AutoCheck Pro - Form Processing
 * Handles inspection form submission and report generation
 */

// Load Dompdf
require_once __DIR__ . '/vendor/autoload.php';
use Dompdf\Dompdf;
use Dompdf\Options;

// Error reporting for development (remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 0);

// Configuration
$uploadDir = __DIR__ . '/uploads/';
$reportsDir = __DIR__ . '/reports/';
$maxFileSize = 5 * 1024 * 1024; // 5MB
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

// Create directories if they don't exist
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}
if (!is_dir($reportsDir)) {
    mkdir($reportsDir, 0755, true);
}

// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: inspection.php');
    exit;
}

// Sanitize function
function sanitize($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

// Collect form data
$data = [
    'inspector_name' => sanitize($_POST['inspector_name'] ?? ''),
    'inspection_date' => sanitize($_POST['inspection_date'] ?? date('Y-m-d')),
    'company_name' => sanitize($_POST['company_name'] ?? ''),
    'inspector_email' => sanitize($_POST['inspector_email'] ?? ''),
    'vehicle_make' => sanitize($_POST['vehicle_make'] ?? ''),
    'vehicle_model' => sanitize($_POST['vehicle_model'] ?? ''),
    'vehicle_year' => sanitize($_POST['vehicle_year'] ?? ''),
    'vehicle_color' => sanitize($_POST['vehicle_color'] ?? ''),
    'vin_number' => sanitize($_POST['vin_number'] ?? ''),
    'license_plate' => sanitize($_POST['license_plate'] ?? ''),
    'mileage' => sanitize($_POST['mileage'] ?? ''),
    'transmission' => sanitize($_POST['transmission'] ?? ''),
    'additional_notes' => sanitize($_POST['additional_notes'] ?? ''),
    'overall_rating' => sanitize($_POST['overall_rating'] ?? ''),
    'checks' => $_POST['checks'] ?? [],
];

// Collect ratings
$ratings = [];
foreach ($_POST as $key => $value) {
    if (strpos($key, 'rating_') === 0) {
        $ratings[str_replace('rating_', '', $key)] = sanitize($value);
    }
}
$data['ratings'] = $ratings;

// Validate required fields
$requiredFields = ['inspector_name', 'inspection_date', 'vehicle_make', 'vehicle_model', 'vehicle_year', 'mileage', 'overall_rating'];
foreach ($requiredFields as $field) {
    if (empty($data[$field])) {
        header('Location: inspection.php?error=' . urlencode("Please fill in all required fields."));
        exit;
    }
}

// Handle photo uploads
$uploadedPhotos = [];
if (isset($_FILES['photos']) && !empty($_FILES['photos']['name'][0])) {
    $photoLabels = ['Front View', 'Rear View', 'Left Side', 'Right Side', 'Dashboard', 'Interior', 'Engine Bay', 'Additional'];

    for ($i = 0; $i < count($_FILES['photos']['name']); $i++) {
        if ($_FILES['photos']['error'][$i] === UPLOAD_ERR_OK) {
            $tmpName = $_FILES['photos']['tmp_name'][$i];
            $fileName = $_FILES['photos']['name'][$i];
            $fileSize = $_FILES['photos']['size'][$i];
            $fileType = $_FILES['photos']['type'][$i];

            // Validate file
            if ($fileSize > $maxFileSize) {
                continue; // Skip files that are too large
            }

            if (!in_array($fileType, $allowedTypes)) {
                continue; // Skip invalid file types
            }

            // Generate unique filename
            $extension = pathinfo($fileName, PATHINFO_EXTENSION);
            $newFileName = uniqid('photo_') . '.' . $extension;
            $destination = $uploadDir . $newFileName;

            if (move_uploaded_file($tmpName, $destination)) {
                $uploadedPhotos[] = [
                    'path' => 'uploads/' . $newFileName,
                    'label' => $photoLabels[$i] ?? 'Photo ' . ($i + 1)
                ];
            }
        }
    }
}
$data['photos'] = $uploadedPhotos;

// Generate report ID
$reportId = 'RPT-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));
$data['report_id'] = $reportId;
$data['base_path'] = __DIR__;

// Generate HTML for PDF
$reportHtml = generateReport($data);

// Create PDF using Dompdf
$options = new Options();
$options->set('isRemoteEnabled', true);
$options->set('isHtml5ParserEnabled', true);

$dompdf = new Dompdf($options);
$dompdf->loadHtml($reportHtml);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

// Save PDF to file
$reportFileName = $reportId . '.pdf';
$reportPath = $reportsDir . $reportFileName;
file_put_contents($reportPath, $dompdf->output());

// Redirect to success page
header('Location: report.php?id=' . urlencode($reportId));
exit;

/**
 * Generate HTML Report with Cover Page
 */
function generateReport($data) {
    $ratingLabels = [
        'excellent' => ['label' => 'Excellent', 'color' => '#22c55e'],
        'good' => ['label' => 'Good', 'color' => '#10b981'],
        'fair' => ['label' => 'Fair', 'color' => '#fbbf24'],
        'poor' => ['label' => 'Poor', 'color' => '#ef4444'],
    ];

    $checkLabels = [
        'exterior_body' => 'Exterior Body Condition',
        'paint' => 'Paint Condition',
        'glass' => 'Glass & Windows',
        'lights' => 'Lights & Signals',
        'engine' => 'Engine Performance',
        'transmission_check' => 'Transmission',
        'brakes' => 'Brakes',
        'suspension' => 'Suspension',
        'tires' => 'Tires Condition',
        'wheels' => 'Wheels & Rims',
        'seats' => 'Seats & Upholstery',
        'dashboard_check' => 'Dashboard & Controls',
        'ac' => 'A/C & Heating',
        'electronics' => 'Electronics & Infotainment',
    ];

    $overallRating = $ratingLabels[$data['overall_rating']] ?? ['label' => 'N/A', 'color' => '#64748b'];

    // SVG Logo for PDF
    $logoHtml = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 180" width="320" style="margin-bottom: 20px;">
        <defs>
            <linearGradient id="bgGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                <stop offset="0%" style="stop-color:#ff0000"/>
                <stop offset="40%" style="stop-color:#8b0000"/>
                <stop offset="100%" style="stop-color:#1a1a1a"/>
            </linearGradient>
        </defs>
        <rect width="400" height="180" fill="url(#bgGradient)" rx="10"/>
        <g fill="none" stroke="#ffffff" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" transform="translate(80, 25) scale(1.2)">
            <path d="M10,70 Q25,65 50,60 Q80,55 100,50 L120,45 Q150,35 180,40 Q200,45 210,55 L220,60 Q235,62 245,68 Q250,72 245,75 L235,75 Q230,60 210,58 Q195,56 185,70 L70,70 Q60,56 45,58 Q30,60 25,75 L15,75 Q5,72 10,70 Z"/>
            <path d="M105,48 Q130,35 160,38 Q185,42 195,52 L108,52 Q105,50 105,48 Z" fill="#ffffff" fill-opacity="0.2"/>
            <path d="M5,68 Q15,65 30,65"/>
            <path d="M220,62 Q235,60 250,65"/>
        </g>
        <text x="200" y="150" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="28" font-weight="bold" letter-spacing="3">VERIDANZ EMPIRE</text>
    </svg>';

    $photosHtml = '';
    if (!empty($data['photos'])) {
        $photosHtml = '<div class="section photos-section"><h3>Vehicle Photos</h3><div class="photos-grid">';
        foreach ($data['photos'] as $photo) {
            $imagePath = $data['base_path'] . '/' . $photo['path'];
            if (file_exists($imagePath)) {
                $imageData = base64_encode(file_get_contents($imagePath));
                $imageType = pathinfo($imagePath, PATHINFO_EXTENSION);
                $mimeType = ($imageType === 'jpg') ? 'jpeg' : $imageType;
                $photosHtml .= '<div class="photo-item"><img src="data:image/' . $mimeType . ';base64,' . $imageData . '" alt="' . htmlspecialchars($photo['label']) . '"><span>' . htmlspecialchars($photo['label']) . '</span></div>';
            }
        }
        $photosHtml .= '</div></div>';
    }

    $checklistHtml = '';
    if (!empty($data['checks'])) {
        $checklistHtml = '<div class="section checklist-section"><h3>Inspection Checklist</h3><table class="checklist-table"><thead><tr><th>Item</th><th>Rating</th></tr></thead><tbody>';
        foreach ($data['checks'] as $check) {
            $label = $checkLabels[$check] ?? ucwords(str_replace('_', ' ', $check));
            $rating = $data['ratings'][$check] ?? 'good';
            $ratingInfo = $ratingLabels[$rating] ?? ['label' => 'N/A', 'color' => '#64748b'];
            $checklistHtml .= '<tr><td>' . htmlspecialchars($label) . '</td><td><span class="rating-badge" style="background-color: ' . $ratingInfo['color'] . '">' . htmlspecialchars($ratingInfo['label']) . '</span></td></tr>';
        }
        $checklistHtml .= '</tbody></table></div>';
    }

    $html = '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inspection Report - ' . htmlspecialchars($data['report_id']) . '</title>
    <style>
        @page { margin: 0; }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: Arial, sans-serif; color: #1e293b; line-height: 1.6; font-size: 12px; }

        /* Cover Page */
        .cover-page {
            width: 100%;
            height: 100%;
            min-height: 1120px;
            background: linear-gradient(180deg, #dc2626 0%, #7f1d1d 50%, #1a1a1a 100%);
            display: table;
            page-break-after: always;
        }
        .cover-content {
            display: table-cell;
            vertical-align: middle;
            text-align: center;
            padding: 60px;
        }
        .cover-logo {
            max-width: 280px;
            margin-bottom: 30px;
        }
        .cover-company {
            color: #ffffff;
            font-size: 42px;
            font-weight: bold;
            letter-spacing: 3px;
            margin-bottom: 50px;
            text-transform: uppercase;
        }
        .cover-title {
            color: #ffffff;
            font-size: 28px;
            font-weight: normal;
            margin-bottom: 60px;
            padding: 20px 40px;
            border: 2px solid rgba(255,255,255,0.3);
            display: inline-block;
        }
        .cover-details {
            color: rgba(255,255,255,0.9);
            font-size: 16px;
            margin-top: 80px;
        }
        .cover-details p {
            margin: 15px 0;
        }
        .cover-details strong {
            color: #ffffff;
        }
        .cover-report-id {
            margin-top: 60px;
            color: rgba(255,255,255,0.6);
            font-size: 14px;
        }

        /* Report Pages */
        .report-page { padding: 40px; page-break-before: always; }
        .report-page:first-of-type { page-break-before: auto; }

        .page-header {
            border-bottom: 3px solid #dc2626;
            padding-bottom: 15px;
            margin-bottom: 30px;
        }
        .page-header h1 {
            color: #dc2626;
            font-size: 24px;
            margin: 0;
        }
        .page-header p {
            color: #64748b;
            font-size: 11px;
            margin-top: 5px;
        }

        .section { margin-bottom: 30px; }
        .section h3 {
            color: #1e293b;
            font-size: 16px;
            margin-bottom: 15px;
            padding-bottom: 8px;
            border-bottom: 2px solid #e2e8f0;
        }

        .info-grid {
            width: 100%;
            border-collapse: collapse;
        }
        .info-grid td {
            width: 50%;
            padding: 10px;
            vertical-align: top;
        }
        .info-item {
            background: #f8fafc;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 8px;
        }
        .info-item label {
            font-size: 10px;
            color: #64748b;
            display: block;
            margin-bottom: 3px;
            text-transform: uppercase;
        }
        .info-item span {
            font-weight: bold;
            color: #1e293b;
            font-size: 13px;
        }

        .overall-rating {
            text-align: center;
            padding: 25px;
            background: #f8fafc;
            border-radius: 10px;
        }
        .overall-rating h4 {
            color: #64748b;
            font-size: 12px;
            margin-bottom: 10px;
            text-transform: uppercase;
        }
        .rating-display {
            display: inline-block;
            padding: 12px 35px;
            border-radius: 25px;
            color: white;
            font-size: 18px;
            font-weight: bold;
        }

        .photos-grid {
            width: 100%;
        }
        .photos-grid td {
            width: 25%;
            padding: 5px;
            vertical-align: top;
        }
        .photo-item {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            overflow: hidden;
        }
        .photo-item img {
            width: 100%;
            height: 100px;
            object-fit: cover;
            display: block;
        }
        .photo-item span {
            display: block;
            padding: 6px;
            text-align: center;
            background: #f8fafc;
            font-size: 9px;
            color: #64748b;
        }

        .checklist-table {
            width: 100%;
            border-collapse: collapse;
        }
        .checklist-table th, .checklist-table td {
            padding: 10px 12px;
            text-align: left;
            border-bottom: 1px solid #e2e8f0;
            font-size: 11px;
        }
        .checklist-table th {
            background: #f8fafc;
            color: #1e293b;
            font-weight: bold;
        }
        .rating-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 15px;
            color: white;
            font-size: 10px;
            font-weight: bold;
        }

        .notes-section {
            background: #f8fafc;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid #dc2626;
        }
        .notes-section p {
            color: #1e293b;
            font-size: 11px;
        }

        .report-footer {
            text-align: center;
            padding: 20px;
            border-top: 1px solid #e2e8f0;
            color: #64748b;
            font-size: 10px;
            margin-top: 40px;
        }
    </style>
</head>
<body>
    <!-- Cover Page -->
    <div class="cover-page">
        <div class="cover-content">
            ' . $logoHtml . '
            <h1 class="cover-company">VERIDANZ EMPIRE</h1>
            <div class="cover-title">Vehicle Inspection Report</div>
            <div class="cover-details">
                <p><strong>Inspected By:</strong> ' . htmlspecialchars($data['inspector_name']) . '</p>
                <p><strong>Inspection Date:</strong> ' . htmlspecialchars(date('F j, Y', strtotime($data['inspection_date']))) . '</p>
                <p><strong>Vehicle:</strong> ' . htmlspecialchars($data['vehicle_year'] . ' ' . $data['vehicle_make'] . ' ' . $data['vehicle_model']) . '</p>
            </div>
            <div class="cover-report-id">Report ID: ' . htmlspecialchars($data['report_id']) . '</div>
        </div>
    </div>

    <!-- Report Content -->
    <div class="report-page">
        <div class="page-header">
            <h1>VERIDANZ EMPIRE</h1>
            <p>Vehicle Inspection Report | ' . htmlspecialchars($data['report_id']) . ' | ' . htmlspecialchars(date('F j, Y', strtotime($data['inspection_date']))) . '</p>
        </div>

        <div class="section">
            <h3>Vehicle Information</h3>
            <table class="info-grid">
                <tr>
                    <td>
                        <div class="info-item">
                            <label>Make</label>
                            <span>' . htmlspecialchars($data['vehicle_make']) . '</span>
                        </div>
                    </td>
                    <td>
                        <div class="info-item">
                            <label>Model</label>
                            <span>' . htmlspecialchars($data['vehicle_model']) . '</span>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="info-item">
                            <label>Year</label>
                            <span>' . htmlspecialchars($data['vehicle_year']) . '</span>
                        </div>
                    </td>
                    <td>
                        <div class="info-item">
                            <label>Color</label>
                            <span>' . (!empty($data['vehicle_color']) ? htmlspecialchars($data['vehicle_color']) : 'N/A') . '</span>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="info-item">
                            <label>Mileage</label>
                            <span>' . htmlspecialchars(number_format((int)$data['mileage'])) . '</span>
                        </div>
                    </td>
                    <td>
                        <div class="info-item">
                            <label>Transmission</label>
                            <span>' . (!empty($data['transmission']) ? ucfirst(htmlspecialchars($data['transmission'])) : 'N/A') . '</span>
                        </div>
                    </td>
                </tr>
                ' . (!empty($data['vin_number']) || !empty($data['license_plate']) ? '
                <tr>
                    ' . (!empty($data['vin_number']) ? '<td><div class="info-item"><label>VIN</label><span>' . htmlspecialchars($data['vin_number']) . '</span></div></td>' : '<td></td>') . '
                    ' . (!empty($data['license_plate']) ? '<td><div class="info-item"><label>License Plate</label><span>' . htmlspecialchars($data['license_plate']) . '</span></div></td>' : '<td></td>') . '
                </tr>' : '') . '
            </table>
        </div>

        <div class="section">
            <h3>Overall Vehicle Rating</h3>
            <div class="overall-rating">
                <h4>Vehicle Condition</h4>
                <div class="rating-display" style="background-color: ' . $overallRating['color'] . '">' . htmlspecialchars($overallRating['label']) . '</div>
            </div>
        </div>

        ' . $checklistHtml . '

        ' . (!empty($data['additional_notes']) ? '<div class="section"><h3>Additional Notes</h3><div class="notes-section"><p>' . nl2br(htmlspecialchars($data['additional_notes'])) . '</p></div></div>' : '') . '
    </div>

    ' . (!empty($data['photos']) ? '
    <div class="report-page">
        <div class="page-header">
            <h1>VERIDANZ EMPIRE</h1>
            <p>Vehicle Photos | ' . htmlspecialchars($data['report_id']) . '</p>
        </div>
        ' . $photosHtml . '
    </div>' : '') . '

    <div class="report-footer">
        <p>This report was generated by Veridanz Empire on ' . date('F j, Y \a\t g:i A') . '</p>
        <p>Report ID: ' . htmlspecialchars($data['report_id']) . '</p>
    </div>
</body>
</html>';

    return $html;
}
