<?php
ob_start();
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }

require_once('../titancore/titanconfig.php');

// Fix Database Encoding
mysqli_set_charset($conn, "utf8mb4");
mysqli_query($conn, "SET NAMES 'utf8mb4'");
mysqli_query($conn, "SET CHARACTER SET 'utf8mb4'");

require_once('../titancore/titanheader.php');

$uid = $_SESSION['user_id'];
$utype = $_SESSION['utype'] ?? $_SESSION['user_type'] ?? 'Retailer';

$filter = ($utype == 'TitanAdmin') ? "" : "WHERE user_id = '$uid'";
$query = "SELECT * FROM engine_rc_history $filter ORDER BY id DESC";
$result = $conn->query($query);
?>

<div class="row mb-3">
    <div class="col">
        <div class="card bg-100 shadow-none border">
            <div class="row gx-0 flex-between-center p-3">
                <div class="col-sm-auto d-flex align-items-center">
                    <div class="icon-item bg-warning-subtle shadow-none me-3">
                        <span class="fas fa-list text-warning fs-4"></span>
                    </div>
                    <div>
                        <h6 class="text-warning fs-10 mb-0">History Log</h6>
                        <h4 class="text-primary fw-bold mb-0">Engine to RC <span class="fw-medium">Records</span></h4>
                    </div>
                </div>
                <div class="col-md-auto mt-3 mt-md-0">
                    <a href="Engine_To_Rc_Details.php" class="btn btn-sm btn-warning shadow-none fw-bold">
                        <i class="fas fa-search me-1"></i> Search New Engine
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card mb-3 border-0 shadow-sm border-top border-4 border-warning">
    <div class="card-body p-0">
        <div class="table-responsive scrollbar">
            <table class="table table-sm table-striped fs-10 mb-0 text-center align-middle">
                <thead class="bg-200 text-900">
                    <tr>
                        <th class="py-2">#ID</th>
                        <th>Engine No.</th>
                        <th>Registration No.</th>
                        <th>Owner Name</th>
                        <th>Amount</th>
                        <th>Date & Time</th>
                        <th class="text-end pe-4">Action</th>
                    </tr>
                </thead>
                <tbody class="list">
                    <?php if($result && $result->num_rows > 0): ?>
                        <?php while($row = $result->fetch_assoc()): 
                            // Secure JSON data pass kar rahe hain HTML attribute me
                            $secure_json_data = htmlspecialchars($row['vehicle_data'], ENT_QUOTES, 'UTF-8');
                            
                            // Format amount
                            $amount = !empty($row['deducted_amount']) ? '₹' . number_format($row['deducted_amount'], 2) : '₹3.00';
                        ?>
                            <tr>
                                <td class="py-3 fw-bold">#<?php echo $row['id']; ?></td>
                                <td>
                                    <span class="badge badge-subtle-warning fs-11 px-3 py-2 font-monospace border border-warning">
                                        <i class="fas fa-cog me-1"></i> <?php echo htmlspecialchars($row['engine_no']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge badge-subtle-primary fs-11 px-3 py-2 border border-primary">
                                        <i class="fas fa-id-card me-1"></i> <?php echo htmlspecialchars($row['registration_no'] ?? 'N/A'); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge badge-subtle-secondary fs-11 px-3 py-2 border border-secondary">
                                        <i class="fas fa-user me-1"></i> <?php echo htmlspecialchars($row['full_name'] ?? 'N/A'); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge badge-subtle-danger fs-11 px-3 py-2 border border-danger">
                                        <i class="fas fa-rupee-sign me-1"></i> <?php echo $amount; ?>
                                    </span>
                                </td>
                                <td class="text-600">
                                    <?php echo date('d M Y, h:i A', strtotime($row['created_at'])); ?>
                                </td>
                                <td class="text-end pe-4">
                                    <button class="btn btn-sm btn-falcon-warning fw-bold px-3 shadow-none" 
                                            data-json="<?php echo $secure_json_data; ?>" 
                                            data-engine="<?php echo htmlspecialchars($row['engine_no']); ?>" 
                                            data-registration="<?php echo htmlspecialchars($row['registration_no'] ?? 'N/A'); ?>"
                                            onclick="viewDetails(this)">
                                        <i class="fas fa-eye me-1"></i> View Details
                                    </button>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" class="py-4 text-500 fst-italic">
                                <i class="fas fa-inbox me-2"></i>No records found. Search an engine number first.
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    function viewDetails(btn) {
        let engine = btn.getAttribute('data-engine');
        let registration = btn.getAttribute('data-registration');
        
        // Direct JSON Parse - FULL DATA
        let rawData = btn.getAttribute('data-json');
        let data = JSON.parse(rawData);

        // Extract all details
        let vehicle = data.vehicle_details || {};
        let customer = data.customer_details || {};
        let nominee = data.nominee_details || {};
        let metaData = data.meta_data || {};
        let signzyData = metaData.signzy_response || {};
        let signzyResult = signzyData.result || {};

        // Build HTML Table dynamically - FULL RESPONSE
        let htmlTable = `
            <div class="table-responsive mt-3" style="max-height: 500px; overflow-y: auto;">
                <!-- Customer Details -->
                <h6 class="text-warning mb-2"><i class="fas fa-user me-2"></i>Customer Details</h6>
                <table class="table table-bordered table-sm fs-10 text-start align-middle mb-3">
                    <tbody>
                        <tr><td class="fw-bold bg-200" style="width: 35%;">Full Name</td><td><strong>${customer.full_name || 'N/A'}</strong></td></tr>
                        <tr><td class="fw-bold bg-200">Customer Type</td><td>${data.customer_type || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Address Line</td><td>${customer.communication_address?.address_line || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Pincode</td><td>${customer.communication_address?.pincode || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Is Accordion Completed</td><td>${customer.is_accordion_completed ? 'Yes' : 'No'}</td></tr>
                        <tr><td class="fw-bold bg-200">Is Claimed</td><td>${data.is_claimed ? 'Yes' : 'No'}</td></tr>
                        <tr><td class="fw-bold bg-200">Is Ownership Transfer</td><td>${data.is_ownership_transfer ? 'Yes' : 'No'}</td></tr>
                    </tbody>
                </table>

                <!-- Nominee Details -->
                <h6 class="text-warning mb-2"><i class="fas fa-user-tie me-2"></i>Nominee Details</h6>
                <table class="table table-bordered table-sm fs-10 text-start align-middle mb-3">
                    <tbody>
                        <tr><td class="fw-bold bg-200" style="width: 35%;">Is Accordion Completed</td><td>${nominee.is_accordion_completed ? 'Yes' : 'No'}</td></tr>
                    </tbody>
                </table>

                <!-- Vehicle Details -->
                <h6 class="text-warning mb-2"><i class="fas fa-car me-2"></i>Vehicle Details</h6>
                <table class="table table-bordered table-sm fs-10 text-start align-middle mb-3">
                    <tbody>
                        <tr><td class="fw-bold bg-200" style="width: 35%;">Registration No.</td><td><strong class="text-primary">${vehicle.registration_no || 'N/A'}</strong></td></tr>
                        <tr><td class="fw-bold bg-200">Engine No.</td><td>${vehicle.engine_no || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Chassis No.</td><td>${vehicle.chassis_no || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Registration Date</td><td>${vehicle.registration_date || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Manufacture Date</td><td>${vehicle.manufacture_date || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Vehicle Color</td><td>${vehicle.vehicle_color || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Vehicle Type</td><td>${vehicle.vehicle_type || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Is Vehicle Financed</td><td>${vehicle.is_vehicle_financed ? 'Yes' : 'No'}</td></tr>
                        <tr><td class="fw-bold bg-200">Is Same Location</td><td>${vehicle.is_same_location ? 'Yes' : 'No'}</td></tr>
                        <tr><td class="fw-bold bg-200">Registration Address</td><td>${vehicle.registration_address?.address_line || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Registration Pincode</td><td>${vehicle.registration_address?.pincode || 'N/A'}</td></tr>
                    </tbody>
                </table>

                <!-- Additional Details -->
                <h6 class="text-warning mb-2"><i class="fas fa-info-circle me-2"></i>Additional Details</h6>
                <table class="table table-bordered table-sm fs-10 text-start align-middle mb-3">
                    <tbody>
                        <tr><td class="fw-bold bg-200" style="width: 35%;">Previous Insurer Code</td><td>${data.previous_insurer_code || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Previous Policy Expiry</td><td>${data.previous_policy_exp_date || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Previous Year NCB</td><td>${data.previous_year_ncb || 'N/A'}%</td></tr>
                        <tr><td class="fw-bold bg-200">Previous Policy No.</td><td>${data.previous_policy_number || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">RTO Code</td><td>${data.rb_rto_code || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">MMV ID</td><td>${data.rb_mmv_id || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Chassis Number</td><td>${data.chassis_number || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Engine Number</td><td>${data.engine_number || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Registration Day</td><td>${data.registration_day || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Registration Month</td><td>${data.registration_month || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Registration Year</td><td>${data.registration_year || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Manufactured Month</td><td>${data.manufactured_month || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Manufactured Year</td><td>${data.manufactured_year || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Is Two Wheeler</td><td>${data.is_two_wheeler ? 'Yes' : 'No'}</td></tr>
                        <tr><td class="fw-bold bg-200">Is Four Wheeler</td><td>${data.is_four_wheeler ? 'Yes' : 'No'}</td></tr>
                        <tr><td class="fw-bold bg-200">Is Commercial</td><td>${data.is_commercial ? 'Yes' : 'No'}</td></tr>
                        <tr><td class="fw-bold bg-200">Registration Number</td><td><strong>${data.registration_number || 'N/A'}</strong></td></tr>
                        <tr><td class="fw-bold bg-200">Provider</td><td>${data.Provider || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Status</td><td><span class="badge bg-success">${data.status || 'N/A'}</span></td></tr>
                    </tbody>
                </table>

                <!-- Signzy Response (Meta Data) -->
                <h6 class="text-warning mb-2"><i class="fas fa-database me-2"></i>Signzy Response (Meta Data)</h6>
                <table class="table table-bordered table-sm fs-10 text-start align-middle">
                    <tbody>
                        <tr><td class="fw-bold bg-200" style="width: 35%;">Reg No</td><td><strong>${signzyResult.regNo || 'N/A'}</strong></td></tr>
                        <tr><td class="fw-bold bg-200">Class</td><td>${signzyResult.class || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Chassis</td><td>${signzyResult.chassis || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Engine</td><td>${signzyResult.engine || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Vehicle Manufacturer</td><td>${signzyResult.vehicleManufacturerName || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Model</td><td><strong>${signzyResult.model || 'N/A'}</strong></td></tr>
                        <tr><td class="fw-bold bg-200">Vehicle Colour</td><td>${signzyResult.vehicleColour || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Type</td><td>${signzyResult.type || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Norms Type</td><td>${signzyResult.normsType || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Body Type</td><td>${signzyResult.bodyType || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Owner Count</td><td>${signzyResult.ownerCount || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Owner</td><td>${signzyResult.owner || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Status</td><td><span class="badge bg-success">${signzyResult.status || 'N/A'}</span></td></tr>
                        <tr><td class="fw-bold bg-200">Status As On</td><td>${signzyResult.statusAsOn || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Reg Authority</td><td>${signzyResult.regAuthority || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Reg Date</td><td>${signzyResult.regDate || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Vehicle Manufacturing Month Year</td><td>${signzyResult.vehicleManufacturingMonthYear || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">RC Expiry Date</td><td><strong>${signzyResult.rcExpiryDate || 'N/A'}</strong></td></tr>
                        <tr><td class="fw-bold bg-200">Vehicle Tax Upto</td><td>${signzyResult.vehicleTaxUpto || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Insurance Company</td><td>${signzyResult.vehicleInsuranceCompanyName || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Insurance Upto</td><td>${signzyResult.vehicleInsuranceUpto || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Insurance Policy No.</td><td>${signzyResult.vehicleInsurancePolicyNumber || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">RC Financer</td><td>${signzyResult.rcFinancer || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Present Address</td><td>${signzyResult.presentAddress || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Permanent Address</td><td>${signzyResult.permanentAddress || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Cubic Capacity</td><td>${signzyResult.vehicleCubicCapacity || 'N/A'} CC</td></tr>
                        <tr><td class="fw-bold bg-200">Gross Vehicle Weight</td><td>${signzyResult.grossVehicleWeight || 'N/A'} KG</td></tr>
                        <tr><td class="fw-bold bg-200">Unladen Weight</td><td>${signzyResult.unladenWeight || 'N/A'} KG</td></tr>
                        <tr><td class="fw-bold bg-200">Vehicle Category</td><td>${signzyResult.vehicleCategory || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Cylinders No.</td><td>${signzyResult.vehicleCylindersNo || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Seat Capacity</td><td>${signzyResult.vehicleSeatCapacity || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Sleeper Capacity</td><td>${signzyResult.vehicleSleeperCapacity || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Standing Capacity</td><td>${signzyResult.vehicleStandingCapacity || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Wheelbase</td><td>${signzyResult.wheelbase || 'N/A'} mm</td></tr>
                        <tr><td class="fw-bold bg-200">Vehicle Number</td><td><strong>${signzyResult.vehicleNumber || 'N/A'}</strong></td></tr>
                        <tr><td class="fw-bold bg-200">PUCC Number</td><td>${signzyResult.puccNumber || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Permit Issue Date</td><td>${signzyResult.permitIssueDate || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Permit Valid From</td><td>${signzyResult.permitValidFrom || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Permit Valid Upto</td><td>${signzyResult.permitValidUpto || 'N/A'}</td></tr>
                        <tr><td class="fw-bold bg-200">Is Commercial</td><td>${signzyResult.isCommercial ? 'Yes' : 'No'}</td></tr>
                        <tr><td class="fw-bold bg-200">RTO Code</td><td>${signzyResult.rtoCode || 'N/A'}</td></tr>
                    </tbody>
                </table>
            </div>
        `;

        // Pop-up show karna
        Swal.fire({
            title: `<h5 class="mb-0 text-warning"><i class="fas fa-car me-2"></i>Engine to RC - Full Details</h5>
                    <div class="mt-1">
                        <span class="badge badge-subtle-warning fs-11">Engine: ${engine}</span>
                        <span class="badge badge-subtle-primary fs-11 ms-2">Registration: ${registration}</span>
                    </div>`,
            html: htmlTable,
            width: '950px',
            confirmButtonText: 'Close',
            customClass: { 
                confirmButton: 'btn btn-warning shadow-none px-4',
                title: 'text-warning'
            },
            buttonsStyling: false
        });
    }
</script>

<?php 
require_once('../titancore/TitanFooter.php'); 
ob_end_flush();
?>