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

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

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

$uid = $_SESSION['user_id'];
$u_name = $_SESSION['user_name'] ?? 'User';

$swal_msg = "";

// 2. Pricing Fetch
$price_check = $conn->query("SELECT price FROM pricing WHERE service_name = 'engine_rc_pdf'");
$service_price = ($price_check && $price_check->num_rows > 0) ? $price_check->fetch_assoc()['price'] : 3.00;

// 3. API Config Fetch from TitanPayment
$api_settings = $conn->query("SELECT titanurl, titan_api_key FROM TitanPayment WHERE id = 1")->fetch_assoc();
$TitanApi_Url = $api_settings['titanurl'] ?? '';
$api_key = $api_settings['titan_api_key'] ?? '';

if (empty($TitanApi_Url) || empty($api_key)) {
    echo "<script>alert('System Error: TitanPayment API URL or Key is not configured.'); window.location.href='titanhome.php';</script>";
    exit();
}

// 4. Handle Verification Logic
if (isset($_POST['verify_btn'])) {
    $input_engine = mysqli_real_escape_string($conn, trim($_POST['engine_number']));
    
    // Validate Engine Number
    if (empty($input_engine) || strlen($input_engine) < 5) {
        $swal_msg = "Swal.fire('Invalid Input!', 'Please enter a valid Engine number.', 'error');";
    } else {
        // Wallet Check
        $user_wallet = $conn->query("SELECT wallet FROM users WHERE id = '$uid'")->fetch_assoc()['wallet'];
        
        if ($user_wallet < $service_price) {
            $swal_msg = "Swal.fire('Low Balance!', 'You need ₹$service_price in your wallet to use this service.', 'warning');";
        } else {
            // Build API URL
            $endpoint = rtrim($TitanApi_Url, '/') . "/api/v1/Engine_To_RC_Pdf.php?api_key=" . urlencode($api_key) . "&engine_no=" . urlencode($input_engine);
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $endpoint);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 40); // Timeout slightly increased for PDF payload
            $api_response = curl_exec($ch);
            $curl_error = curl_error($ch);
            curl_close($ch);
            
            if ($api_response) {
                $data = json_decode($api_response, true);
                
                // API uses "100" as status for Success
                if (isset($data['result']['status']) && (string)$data['result']['status'] === '100') {
                    
                    // Get transaction details
                    $transaction = $data['transaction'] ?? [];
                    $transaction_id = mysqli_real_escape_string($conn, $transaction['transaction_id'] ?? 'TXN'.time());
                    $deducted_amount = $transaction['deducted_amount'] ?? $service_price;
                    $old_balance = $transaction['old_balance'] ?? $user_wallet;
                    $new_balance = $transaction['new_balance'] ?? ($user_wallet - $service_price);
                    
                    // Get vehicle details directly from result
                    $result_data = $data['result'];
                    $registration_no = mysqli_real_escape_string($conn, $result_data['vehicle_number'] ?? '');
                    $chassis_number = mysqli_real_escape_string($conn, $result_data['chassis_number'] ?? '');
                    $full_name = mysqli_real_escape_string($conn, $result_data['owner_name'] ?? '');
                    $base64_pdf = mysqli_real_escape_string($conn, $result_data['base64_pdf'] ?? '');
                    
                    // Strip base64 from main JSON to save DB space from duplication
                    $json_data_without_pdf = $result_data;
                    unset($json_data_without_pdf['base64_pdf']);
                    $full_data_json = mysqli_real_escape_string($conn, json_encode($json_data_without_pdf));
                    
                    $ip = mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']);
                    
                    // Deduct Wallet
                    $conn->query("UPDATE users SET wallet = wallet - $service_price WHERE id = '$uid'");
                    
                    // Save to Database History Table
                    $insert = "INSERT INTO engine_rc_pdf_history 
                               (user_id, engine_no, chassis_number, registration_no, full_name, vehicle_data, base64_pdf, 
                                ip_used, provider, transaction_id, deducted_amount, old_balance, new_balance, created_at) 
                               VALUES (
                                   '$uid', 
                                   '$input_engine', 
                                   '$chassis_number',
                                   '$registration_no', 
                                   '$full_name', 
                                   '$full_data_json', 
                                   '$base64_pdf',
                                   '$ip', 
                                   'TitanApi', 
                                   '$transaction_id', 
                                   '$deducted_amount', 
                                   '$old_balance', 
                                   '$new_balance', 
                                   NOW()
                               )";
                    
                    if ($conn->query($insert)) {
                        $swal_msg = "Swal.fire('Success!', 'Engine to RC PDF Fetched Successfully!', 'success').then(() => { window.location.href='engine_rc_pdf_history.php'; });";
                    } else {
                        $swal_msg = "Swal.fire('Database Error!', 'Fetched successfully but failed to save history.', 'error');";
                    }
                    
                } else {
                    $err = $data['result']['statusMessage'] ?? $data['message'] ?? 'Verification failed or invalid API response.';
                    $swal_msg = "Swal.fire('Failed!', '" . addslashes($err) . "', 'error');";
                }
            } else {
                $error_msg = $curl_error ?: 'Could not connect to the Master API Server.';
                $swal_msg = "Swal.fire('Server Error!', '" . addslashes($error_msg) . "', 'error');";
            }
        }
    }
}
?>

<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-primary-subtle shadow-none me-3">
                        <span class="fas fa-file-pdf text-primary fs-4"></span>
                    </div>
                    <div>
                        <h6 class="text-primary fs-10 mb-0">Vehicle Services</h6>
                        <h4 class="text-primary fw-bold mb-0">Engine to <span class="text-warning fw-medium">RC PDF</span></h4>
                    </div>
                </div>
                <div class="col-md-auto mt-3 mt-md-0">
                    <a href="engine_rc_pdf_history.php" class="btn btn-sm btn-outline-primary shadow-none fw-bold">
                        <i class="fas fa-list me-1"></i> View History
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row justify-content-center">
    <div class="col-lg-6">
        <div class="card h-100">
            <div class="card-header bg-light border-bottom">
                <h5 class="mb-0 text-primary fw-bold text-center"><i class="fas fa-cogs me-2"></i>Engine Details</h5>
            </div>
            <div class="card-body bg-body-tertiary p-4">
                <div class="alert alert-info border-0 d-flex align-items-center mb-4">
                    <i class="fas fa-rupee-sign fs-3 me-3 text-info"></i>
                    <p class="mb-0 fs-11">Verification charge: <strong>₹<?php echo number_format($service_price, 2); ?></strong> will be deducted from your wallet upon success.</p>
                </div>
                
                <form method="POST">
                    <div class="mb-4">
                        <label class="form-label fw-bold text-900">Engine Number <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text bg-white"><i class="fas fa-cog"></i></span>
                            <input type="text" class="form-control shadow-none" name="engine_number" placeholder="Enter engine number" required>
                        </div>
                        <small class="text-muted">Enter the engine number to fetch RC PDF details</small>
                    </div>
                    
                    <button class="btn btn-primary w-100 fw-bold shadow-none py-2" type="submit" name="verify_btn">
                        <i class="fas fa-search me-2"></i> Fetch RC PDF
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    <?php echo $swal_msg; ?>
</script>

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