<?php
require_once 'header.php';
require_once '../config.php'; // must provide $pdo (PDO instance)

// --- load settings (optional, used for links/display) ---
$stmt = $pdo->query("SELECT * FROM settings ORDER BY id DESC LIMIT 1");
$settings = $stmt->fetch(PDO::FETCH_ASSOC);
$curl = rtrim($settings['url'] ?? '', '/') . '/';
$cname = $settings['domain_name'] ?? 'Parcel System';

// --- data sources ---
$parcelTypes = [
    "Bag of Rice (50kg)",
    "Used Car (Toyota Corolla)",
    "Laptop Computer",
    "Mobile Phones",
    "Shoes and Clothes",
    "Industrial Equipment",
    "Documents (Confidential)",
    "Television Set",
    "Motorcycle",
    "Furniture (Wooden Table)"
];

$companies = [
    ["Global Freight Ltd", "1234 Harbor Street, New York, USA"],
    ["TransWorld Logistics", "221B Baker Street, London, UK"],
    ["EuroCargo Express", "45 Rue de Paris, Paris, France"],
    ["Nippon Transport", "5-2-1 Ginza, Chuo-ku, Tokyo, Japan"],
    ["Aussie Logistics", "99 George St, Sydney, Australia"],
    ["Berlin Cargo", "Kaiserstraße 88, Berlin, Germany"],
    ["Maple Movers", "200 King St, Toronto, Canada"]
];

$countries = ["USA", "UK", "France", "Germany", "Canada", "Australia", "Japan", "China", "UAE", "Nigeria"];

$deliveryStatuses = ["Pending", "In Transit", "On Hold", "Delivered", "Awaiting Pickup"];
$consignmentStatuses = ["Pending Approval", "In Progress", "Dispatched", "Completed"];

// small phone prefixes (optional, used to make phone numbers feel real)
$phonePrefixes = [
    "USA" => "+1", "UK" => "+44", "France" => "+33", "Germany" => "+49",
    "Canada" => "+1", "Australia" => "+61", "Japan" => "+81", "China" => "+86",
    "UAE" => "+971", "Nigeria" => "+234"
];

// --- helpers ---
function uniqueTrackingCode(PDO $pdo) {
    $checkPkg = $pdo->prepare("SELECT 1 FROM packages WHERE tracking_code = ? LIMIT 1");
    $checkGnd = $pdo->prepare("SELECT 1 FROM groundstate WHERE tracking_code = ? LIMIT 1");

    do {
        $code = strtoupper(bin2hex(random_bytes(4))); // 8 hex chars
        $checkPkg->execute([$code]);
        $exists = (bool)$checkPkg->fetchColumn();
        if (!$exists) {
            $checkGnd->execute([$code]);
            $exists = (bool)$checkGnd->fetchColumn();
        }
    } while ($exists);

    return $code;
}

/**
 * Build one parcel as an associative array whose keys match the named placeholders (without the colon).
 * parcel_name and parcel_details use the SAME chosen type so they stay consistent.
 */
function buildOneParcel(PDO $pdo, array $parcelTypes, array $companies, array $countries, array $deliveryStatuses, array $consignmentStatuses, array $phonePrefixes) {
    $type = $parcelTypes[array_rand($parcelTypes)];
    $company = $companies[array_rand($companies)];
    $from = $countries[array_rand($countries)];
    $to = $countries[array_rand($countries)];
    while ($to === $from) {
        $to = $countries[array_rand($countries)];
    }

    $senders = ["John Smith", "Alice Johnson", "Michael Brown", "Fatima Ali", "Chen Wei", "Carlos Lopez", "Aisha Bello"];
    $receivers = ["David Miller", "Sophia Lee", "James Wilson", "Maria Garcia", "Hiroshi Tanaka", "Ahmed Hassan", "Grace Okoro"];

    $sender = $senders[array_rand($senders)];
    $receiver = $receivers[array_rand($receivers)];

    $sPref = $phonePrefixes[$from] ?? "+000";
    $rPref = $phonePrefixes[$to] ?? "+000";

    $tracking = uniqueTrackingCode($pdo);

    return [
        // placeholder name => value (no leading colon)
        'comp_name' => $company[0],
        'comp_location' => $company[1],
        'comp_phone' => $sPref . (string)rand(100000000, 999999999),

        'ship_cost' => rand(50, 500),
        'sub_cost' => rand(10, 150),
        'total_cost' => rand(100, 1000),

        'delivery_status' => $deliveryStatuses[array_rand($deliveryStatuses)],
        'consignment_status' => $consignmentStatuses[array_rand($consignmentStatuses)],
        'billing_name' => $receiver,
        'billing_cost' => rand(50, 300),

        'current_location' => $from,
        'final_destination' => $to,
        'consignment_quantity' => rand(1, 10),

        'arrival_date' => date("Y-m-d", strtotime('+'.rand(2,14).' days')),
        'departure_date' => date("Y-m-d"),
        'arrival_time' => date("H:i:s"),
        'date' => date("Y-m-d"),

        'parcel_name' => $type,
        'parcel_details' => "Shipment of {$type} (standard packaging)",

        'shipment_to' => $to,
        'shipment_from' => $from,
        'tracking_code' => $tracking,

        'recv_name' => $receiver,
        'recv_email' => strtolower(str_replace(' ', '', $receiver)) . rand(100,999) . "@example.com",
        'recv_address' => rand(100,999) . " Main St, {$to}",
        'recv_phone' => $rPref . (string)rand(100000000, 999999999),
        'recv_location' => $to,

        'sdr_name' => $sender,
        'sdr_address' => rand(10,999) . " Market Road, {$from}",
        'sdr_phone' => $sPref . (string)rand(100000000, 999999999),
        'sdr_location' => $from
    ];
}

// --- SQL template for both tables ---
$sqlTemplate = "
INSERT INTO %s (
    comp_name, comp_location, comp_phone, ship_cost, sub_cost, total_cost,
    delivery_status, consignment_status, billing_name, billing_cost, current_location,
    final_destination, consignment_quantity, arrival_date, departure_date, arrival_time, date,
    parcel_name, parcel_details, shipment_to, shipment_from, tracking_code,
    recv_name, recv_email, recv_address, recv_phone, recv_location,
    sdr_name, sdr_address, sdr_phone, sdr_location
) VALUES (
    :comp_name, :comp_location, :comp_phone, :ship_cost, :sub_cost, :total_cost,
    :delivery_status, :consignment_status, :billing_name, :billing_cost, :current_location,
    :final_destination, :consignment_quantity, :arrival_date, :departure_date, :arrival_time, :date,
    :parcel_name, :parcel_details, :shipment_to, :shipment_from, :tracking_code,
    :recv_name, :recv_email, :recv_address, :recv_phone, :recv_location,
    :sdr_name, :sdr_address, :sdr_phone, :sdr_location
)
";

// --- Handle single-parcel generation ---
$success = null;
$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate'])) {
    try {
        // build parcel once (guarantees single tracking code)
        $parcel = buildOneParcel($pdo, $parcelTypes, $companies, $countries, $deliveryStatuses, $consignmentStatuses, $phonePrefixes);

        // prepare statements
        $stmtGround = $pdo->prepare(sprintf($sqlTemplate, 'groundstate'));
        $stmtPackage = $pdo->prepare(sprintf($sqlTemplate, 'packages'));

        // insert into both tables inside a transaction
        $pdo->beginTransaction();
        $stmtGround->execute($parcel);
        $stmtPackage->execute($parcel);
        $pdo->commit();

        $success = [
            'tracking_code' => $parcel['tracking_code'],
            'parcel_name' => $parcel['parcel_name'],
            'from' => $parcel['sdr_location'],
            'to' => $parcel['recv_location']
        ];
    } catch (Exception $ex) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $error = $ex->getMessage();
    }
}
?>




        <div wire:id="0ho7JEz65LVMGIzD4ceZ" wire:initial-data="{&quot;fingerprint&quot;:{&quot;id&quot;:&quot;0ho7JEz65LVMGIzD4ceZ&quot;,&quot;name&quot;:&quot;admin.manage-users&quot;,&quot;locale&quot;:&quot;en&quot;,&quot;path&quot;:&quot;admin\/dashboard\/manageusers&quot;,&quot;method&quot;:&quot;GET&quot;,&quot;v&quot;:&quot;acj&quot;},&quot;effects&quot;:{&quot;listeners&quot;:[],&quot;path&quot;:&quot;https:\/\/xtbtrading.live\/trade\/admin\/dashboard\/manageusers&quot;},&quot;serverMemo&quot;:{&quot;children&quot;:[],&quot;errors&quot;:[],&quot;htmlHash&quot;:&quot;ed570425&quot;,&quot;data&quot;:{&quot;pagenum&quot;:10,&quot;searchvalue&quot;:&quot;&quot;,&quot;orderby&quot;:&quot;id&quot;,&quot;orderdirection&quot;:&quot;desc&quot;,&quot;selectPage&quot;:false,&quot;selectAll&quot;:false,&quot;checkrecord&quot;:[],&quot;selected&quot;:&quot;&quot;,&quot;action&quot;:&quot;Delete&quot;,&quot;username&quot;:null,&quot;fullname&quot;:null,&quot;email&quot;:null,&quot;password&quot;:null,&quot;message&quot;:null,&quot;subject&quot;:null,&quot;plan&quot;:null,&quot;datecreated&quot;:null,&quot;topamount&quot;:null,&quot;toptype&quot;:null,&quot;topcolumn&quot;:&quot;Bonus&quot;,&quot;page&quot;:1,&quot;paginators&quot;:{&quot;page&quot;:1}},&quot;dataMeta&quot;:[],&quot;checksum&quot;:&quot;9e82a6adabccc53607a584c57da8f89b4130352eb62c7aa9cc50f9455ca3c494&quot;}}">
    <div class="main-panel">
        <div class="content bg-light">
            <div class="page-inner">
                <div class="mt-2 mb-4">
                    <h2 class="mb-4">🚚 Generate One Random Parcel</h2>

    <?php if ($success): ?>
        <div class="alert alert-success">
            <h5>Parcel Generated ✅</h5>
            <p><strong>Tracking Code:</strong> <?= htmlspecialchars($success['tracking_code']) ?></p>
            <p><strong>Parcel:</strong> <?= htmlspecialchars($success['parcel_name']) ?></p>
            <p><strong>Route:</strong> <?= htmlspecialchars($success['from']) ?> → <?= htmlspecialchars($success['to']) ?></p>
            <p><a href="tracking.php?code=<?= urlencode($success['tracking_code']) ?>">Track this parcel</a> • <a href="list_parcel.php">View all parcels</a></p>
        </div>
    <?php elseif ($error): ?>
        <div class="alert alert-danger">
            <strong>Error:</strong> <?= htmlspecialchars($error) ?>
        </div>
    <?php endif; ?>

                </div>
                <div>
    </div>                <div>
    </div>                
               
               
               
               
                <div class="mb-5 row">
                    <div class="col-md-12 ">
                        <!--<div class="card shadow p-4 bg-light">-->
                           
                           
                           
                           
                           
                            <div class="card-header">
                                <div class="row">
                                    
                                    
                                    <div class="col-6">
                                             
                                             
                                             
                                              <div class="card-body">
                                <div class="" data-example-id="hoverable-table">
                                    <table class="">
                                        <thead>
                                            <tr>
                                               
                                               
                                                <th><a class="btn btn-primary btn-sm float-right" type="button" href="list_parcel.php">
                                                    <span class="fa fa-gift-plus" data-fa-transform="shrink-3 down-2">&nbsp;Parcel List</span>
                                                   
                                                </a></th>
                                               
                                               
                                              
                                               
                                            </tr>
                                        </thead>
                                        </table>
                                        </div>
                                        </div>
                                        
                                       
                                                                            </div>
                                </div>
                            </div>
                            
                            

<div class="container mt-5">
    <h2>🚚 Generate Random Parcel</h2>
    <form method="POST">
        <button type="submit" name="generate" class="btn btn-primary btn-lg">
            ➕ Generate Parcel
        </button>
    </form>
</div>
