<?php
session_start(); // make sure session is started for instid/accstkn

require __DIR__ . "/vendor/autoload.php"; // ✅ make sure path to autoload.php is correct

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;

if (!isset($_POST['rows']) || !isset($_POST['mobileno'])) {
    die("No data received");
}

$rows = json_decode($_POST['rows'], true);
$mobileno = trim($_POST['mobileno']);

$customer = str_replace(' ', '', $_POST['customer']);

// ✅ use date + time for filename
$today = date("d-m-Y_H-i");

// Save file
$dir = $_SERVER['DOCUMENT_ROOT'] . "/admin/shipmentexcel/";
if (!is_dir($dir)) {
    mkdir($dir, 0777, true);
}

$filename = "shipment_$customer.xlsx";
$filepath = $dir . $filename;

// $fileurl = "https://techfar.in/galeyr/manage/admin/shipmentexcel/" . $filename;

$fileurlsk = "https://apps2ai.com/galaxycargo/manage/admin/shipmentexcel/" . $filename;

// Call TinyURL API
$shorturl = file_get_contents("https://tinyurl.com/api-create.php?url=" . urlencode($fileurlsk));

if ($shorturl) {
    $fileurl = $shorturl;  // replace with shortened link
}


// --- Create Excel ---
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

// headers (must match your HTML table structure)
$headers = [
    "Sr",
    "Shipment No.",
    "Booking Date",
    "Marka",
    "Status",
    "No. of Cartons",
    "Supplier",
    "Description",
    "Pcs",
    "Total CBM",
    "Weight",
    "Origin",
    "Container No.",
    "Sailing Date",
    "Destination",
    "Estimate Date"
];

// Write headers
foreach ($headers as $col => $header) {
    $cell = Coordinate::stringFromColumnIndex($col + 1) . "1";
    $sheet->setCellValue($cell, $header);
}

// Write rows
$rowNum = 2;
foreach ($rows as $row) {
    foreach ($row as $col => $cellValue) {
        $cell = Coordinate::stringFromColumnIndex($col + 1) . $rowNum;
        $sheet->setCellValue($cell, $cellValue);
    }
    $rowNum++;
}

// Save XLSX file
$writer = new Xlsx($spreadsheet);
$writer->save($filepath);

// --- Send WhatsApp to single mobile ---
$instid = $_SESSION["instid"] ?? '';
$accstkn = $_SESSION["accstkn"] ?? '';


if ($mobileno != '' && $instid != '' && $accstkn != '') {

    // Build message body (URL encoded for curl)
    $message = "Hello! Its Your Shipment Details. You can download it here:\n\n$fileurl";
    $messageEnc = escapeshellarg($message);

    // Log file for debugging
    $logFile = "/tmp/whatsapp_textsend_" . time() . ".log";

    // ✅ Async curl command (fire & forget)
    $cmd = "curl -s -X POST " .
        "-F \"number=$mobileno\" " .
        "-F \"type=text\" " .
        "-F \"message=$message\" " .
        "-F \"instance_id=$instid\" " .
        "-F \"access_token=$accstkn\" " .
        "-H 'Accept: application/json' " .
        "https://web.secureleads.in/api/send " .
        "> $logFile 2>&1 &";

    exec($cmd);
    
    // delete file after a short delay in background
    $delCmd = "(sleep 30 && rm -f " . escapeshellarg($filepath) . ") > /dev/null 2>&1 &";
    exec($delCmd);

    
    // ✅ Immediately respond to user
    echo "<script>
        alert('Message Send to Customer');
        setTimeout(function(){ window.close(); }, 1000);
    </script>";

    // Background continues after response
    ignore_user_abort(true);
    set_time_limit(0);

    if (function_exists('fastcgi_finish_request')) {
        fastcgi_finish_request();
    } else {
        ob_end_flush();
        flush();
    }

} else {
    echo "<script>
        alert('Missing mobile / session credentials.');
        window.close();
    </script>";
}

?>