<?php
//process_shipment.php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

require_once '../config.php';
require_once '../get_setting.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require_once 'vendor/PHPMailer/src/Exception.php';
require_once 'vendor/PHPMailer/src/PHPMailer.php';
require_once 'vendor/PHPMailer/src/SMTP.php';

if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("location: admin_login.php");
    exit;
}

$upload_dir = '../uploads/shipment/';

if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

/**
 * Generates the HTML for the beautiful tracking email (Paid/COD).
 */
function get_tracking_email_body($shipment_data, $settings) {
    $logo_url = !empty($settings['site_logo']) ? $settings['site_url'] . '/assets/images/' . $settings['site_logo'] : 'https://via.placeholder.com/150x50?text=Logo';
    $payment_status_text = ($shipment_data['payment_status'] == 'Collect on Delivery') ? 'Collect on Delivery (Payment Due)' : 'Paid';

    $html_body = "
    <div style='font-family: Tahoma, Verdana, sans-serif; background-color: #f4f4f4; padding: 20px;'>
        <div style='max-width: 600px; margin: 0 auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.1);'>
            <div style='background-color: #B00000; padding: 20px; text-align: center;'>
                <img src='{$logo_url}' alt='{$settings['site_title']} Logo' style='max-height: 40px; width: auto; display: block; margin: 0 auto; border-radius: 4px;'>
                <h1 style='color: white; font-size: 24px; margin-top: 15px; margin-bottom: 0;'>Shipment Confirmed!</h1>
            </div>
            
            <div style='padding: 30px; text-align: center; border-bottom: 1px solid #eeeeee;'>
                <p style='color: #B00000; font-size: 16px; font-weight: bold; margin-bottom: 5px;'>Your Shipment is Ready for Tracking:</p>
                <h2 style='font-size: 32px; color: #333333; margin: 5px 0;'>{$shipment_data['tracking_number']}</h2>
                <a href='{$settings['site_url']}/track.php?awb={$shipment_data['tracking_number']}' style='display: inline-block; padding: 10px 25px; margin-top: 15px; background-color: #FFC107; color: #333333; text-decoration: none; border-radius: 5px; font-weight: bold;'>
                    Track Your Package
                </a>
            </div>

            <div style='padding: 30px;'>
                <h3 style='font-size: 20px; color: #B00000; border-bottom: 2px solid #FFC107; padding-bottom: 5px;'>Shipment Summary</h3>
                <table width='100%' cellpadding='10' cellspacing='0' border='0' style='border-collapse: collapse;'>
                    <tr>
                        <td style='border-bottom: 1px solid #f0f0f0; padding: 10px 0; color: #777777;'>Current Status:</td>
                        <td style='border-bottom: 1px solid #f0f0f0; padding: 10px 0; text-align: right; font-weight: bold; color: #333333;'>{$shipment_data['status']}</td>
                    </tr>
                    <tr>
                        <td style='border-bottom: 1px solid #f0f0f0; padding: 10px 0; color: #777777;'>Estimated Delivery:</td>
                        <td style='border-bottom: 1px solid #f0f0f0; padding: 10px 0; text-align: right; font-weight: bold; color: #333333;'>{$shipment_data['estimated_delivery']}</td>
                    </tr>
                    <tr>
                        <td style='border-bottom: 1px solid #f0f0f0; padding: 10px 0; color: #777777;'>Payment Status:</td>
                        <td style='border-bottom: 1px solid #f0f0f0; padding: 10px 0; text-align: right; font-weight: bold; color: #B00000;'>{$payment_status_text}</td>
                    </tr>
                    <tr>
                        <td style='padding: 10px 0; color: #777777;'>Recipient Address:</td>
                        <td style='padding: 10px 0; text-align: right; color: #333333;'>{$shipment_data['receiver_address']}</td>
                    </tr>
                </table>
            </div>

            <div style='background-color: #f4f4f4; padding: 20px; text-align: center; color: #777777; font-size: 12px;'>
                <p>&copy; " . date('Y') . " {$settings['site_title']}. All rights reserved.</p>
                <p style='margin: 0;'>This is an automated notification, please do not reply.</p>
            </div>
        </div>
    </div>
    ";
    return $html_body;
}

/**
 * Generates the HTML for the beautiful payment invoice email (Unpaid).
 */
function get_invoice_email_body($shipment_data, $settings) {
    $logo_url = !empty($settings['site_logo']) ? $settings['site_url'] . '/assets/images/' . $settings['site_logo'] : 'https://via.placeholder.com/150x50?text=Logo';
    $invoice_amount = number_format((float)$shipment_data['amount'], 2);
    $invoice_currency = $shipment_data['currency'] ?? 'USD';
    $item_quantity = $shipment_data['quantity'] ?? 1;
    
    $currency_symbols = [
'USD'=>'$','EUR'=>'€','GBP'=>'£','NGN'=>'₦','CAD'=>'C$','AUD'=>'A$','NZD'=>'NZ$','JPY'=>'¥','CNY'=>'¥','INR'=>'₹','ZAR'=>'R',
'CHF'=>'CHF','SEK'=>'kr','NOK'=>'kr','DKK'=>'kr','RUB'=>'₽','BRL'=>'R$','MXN'=>'MX$','SAR'=>'﷼','AED'=>'د.إ','EGP'=>'E£',
'KES'=>'KSh','GHS'=>'₵','UGX'=>'USh','TZS'=>'TSh','PKR'=>'₨','BDT'=>'৳','LKR'=>'Rs','THB'=>'฿','MYR'=>'RM','IDR'=>'Rp',
'KRW'=>'₩','HKD'=>'HK$','SGD'=>'S$','TRY'=>'₺','PLN'=>'zł','CZK'=>'Kč','HUF'=>'Ft','RON'=>'lei','ILS'=>'₪','KWD'=>'KD',
'QAR'=>'﷼','OMR'=>'﷼','BHD'=>'BD','JOD'=>'JD','MAD'=>'DH','DZD'=>'DA','TND'=>'DT','ETB'=>'Br','AOA'=>'Kz','MWK'=>'MK',
'MZN'=>'MT','ZMW'=>'ZK','BWP'=>'P','NAD'=>'N$','XOF'=>'CFA','XAF'=>'FCFA','LRD'=>'L$','SLL'=>'Le','GMD'=>'D','CVE'=>'$',
'BBD'=>'Bds$','BSD'=>'B$','BZD'=>'BZ$','JMD'=>'J$','TTD'=>'TT$','XCD'=>'EC$','KYD'=>'CI$','BMD'=>'BD$','FJD'=>'FJ$','WST'=>'T',
'TOP'=>'T$','PGK'=>'K','VUV'=>'VT','MOP'=>'P','PHP'=>'₱','MMK'=>'K','LAK'=>'₭','KHR'=>'៛','VND'=>'₫','IRR'=>'﷼','IQD'=>'د.ع',
'LBP'=>'ل.ل','SYR'=>'£','YER'=>'﷼','AFN'=>'؋','NPR'=>'₨','BTN'=>'Nu.','MVR'=>'Rf','SCR'=>'₨','MUR'=>'₨','BND'=>'B$','KZT'=>'₸',
'UZS'=>'лв','TMT'=>'m','GEL'=>'₾','AMD'=>'֏','AZN'=>'₼','BYN'=>'Br','MDL'=>'L','UAH'=>'₴','HRK'=>'kn','RSD'=>'дин','ISK'=>'kr',
'BGN'=>'лв','MKD'=>'ден','ALL'=>'L','BAM'=>'KM','ARS'=>'AR$','CLP'=>'CLP$','COP'=>'COL$','PEN'=>'S/','PYG'=>'₲','UYU'=>'$U',
'VEF'=>'Bs','BOB'=>'Bs','GTQ'=>'Q','HNL'=>'L','NIO'=>'C$','CRC'=>'₡','DOP'=>'RD$','HTG'=>'G','CUC'=>'CUC$','CUP'=>'₱','SRD'=>'SRD$'
];
    $currency_symbol = $currency_symbols[$invoice_currency] ?? $invoice_currency . ' ';
    $due_date = date('Y-m-d', strtotime('+7 days'));

    $html_body = "
    <div style='font-family: Tahoma, Verdana, sans-serif; background-color: #343a40; padding: 20px;'>
        <div style='max-width: 600px; margin: 0 auto; background-color: #ffffff; border-radius: 8px; overflow: hidden;'>
            <div style='background-color: #B00000; color: white; padding: 25px; text-align: center;'>
                <img src='{$logo_url}' alt='{$settings['site_title']} Logo' style='max-height: 40px; width: auto; display: block; margin: 0 auto; filter: brightness(2);'>
                <h1 style='font-size: 28px; margin-top: 15px; margin-bottom: 5px; border-bottom: 2px solid #FFC107; display: inline-block; padding-bottom: 5px;'>INVOICE</h1>
            </div>

            <div style='padding: 30px;'>
                <div style='display: flex; justify-content: space-between; margin-bottom: 20px; border-bottom: 1px dashed #cccccc; padding-bottom: 15px;'>
                    <div style='width: 50%;'>
                        <p style='font-weight: bold; margin: 0; color: #333;'>Invoice For:</p>
                        <p style='margin: 5px 0 0; color: #555;'>{$shipment_data['receiver_name']}</p>
                        <p style='margin: 0; color: #555;'>{$shipment_data['receiver_address']}</p>
                    </div>
                    <div style='width: 50%; text-align: right;'>
                        <p style='font-weight: bold; margin: 0; color: #333;'>Invoice ID: <span style='color: #B00000;'>#{$shipment_data['tracking_number']}</span></p>
                        <p style='margin: 5px 0 0; color: #555;'>Date: " . date('Y-m-d') . "</p>
                        <p style='margin: 0; color: #555;'>Due Date: {$due_date}</p>
                    </div>
                </div>

                <h3 style='font-size: 18px; color: #333333; margin-top: 0;'>Items Summary</h3>
                <table width='100%' cellpadding='10' cellspacing='0' style='border-collapse: collapse; margin-bottom: 25px; border: 1px solid #eeeeee;'>
                    <thead>
                        <tr style='background-color: #f8f8f8;'>
                            <th style='text-align: left; padding: 10px; border-bottom: 1px solid #eeeeee;'>Description</th>
                            <th style='text-align: right; padding: 10px; border-bottom: 1px solid #eeeeee;'>Quantity</th>
                            <th style='text-align: right; padding: 10px; border-bottom: 1px solid #eeeeee;'>Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td style='text-align: left; padding: 10px; border-bottom: 1px solid #eeeeee;'>Shipping Charge for Tracking #{$shipment_data['tracking_number']} ({$shipment_data['weight']} kg)</td>
                            <td style='text-align: right; padding: 10px; border-bottom: 1px solid #eeeeee;'>{$item_quantity}</td>
                            <td style='text-align: right; padding: 10px; border-bottom: 1px solid #eeeeee;'>{$currency_symbol}{$invoice_amount}</td>
                        </tr>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan='2' style='text-align: right; padding: 15px 10px 5px; font-weight: bold; color: #333;'>TOTAL AMOUNT DUE:</td>
                            <td style='text-align: right; padding: 15px 10px 5px; font-weight: bold; font-size: 22px; color: #B00000;'>{$currency_symbol}{$invoice_amount}</td>
                        </tr>
                    </tfoot>
                </table>

                <p style='text-align: center; margin-bottom: 30px; font-size: 16px; color: #333;'>
                    Your shipment confirmation is currently pending payment. Please click below to complete your order.
                </p>

                <p style='text-align: center;'>
                    <a href='{$settings['site_url']}/payment.php?invoice={$shipment_data['tracking_number']}' style='display: inline-block; padding: 12px 30px; background-color: #B00000; color: white; text-decoration: none; border-radius: 5px; font-weight: bold; font-size: 18px; box-shadow: 0 4px 8px rgba(176, 0, 0, 0.4);'>
                        Pay Invoice Now
                    </a>
                </p>
            </div>
        </div>
    </div>
    ";
    return $html_body;
}

/**
 * Sends an email notification using PHPMailer with fallback to PHP mail() function.
 */
function send_email_notification($settings, $recipient_email, $subject, $html_body, &$smtp_config_missing) {
    $smtp_config_missing = false;
    $mail = new PHPMailer(true);

    $from_email = !empty($settings['smtp_from_email']) ? $settings['smtp_from_email'] : 'no-reply@' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
    $from_name = !empty($settings['smtp_from_name']) ? $settings['smtp_from_name'] : ($settings['site_title'] ?? 'Shipping System');

    try {
        if (!empty($settings['use_smtp']) && $settings['use_smtp'] === '1' && !empty($settings['smtp_host'])) {
            $mail->isSMTP();
            $mail->Host       = $settings['smtp_host'];
            $mail->SMTPAuth   = true;
            $mail->Username   = $settings['smtp_username'];
            $mail->Password   = $settings['smtp_password'];
            
            $encryption = strtolower($settings['smtp_encryption'] ?? '');
            if ($encryption === 'ssl') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            } elseif ($encryption === 'tls') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            } else {
                $mail->SMTPAutoTLS = false;
                $mail->SMTPSecure = '';
            }
            $mail->Port       = !empty($settings['smtp_port']) ? (int)$settings['smtp_port'] : 465;
            $from_email = !empty($settings['smtp_from_email']) ? $settings['smtp_from_email'] : $settings['smtp_username'];
        } else {
            $smtp_config_missing = true;
            $mail->isMail();
        }

        $mail->setFrom($from_email, $from_name);
        $mail->addAddress($recipient_email);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $html_body;

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Mailer Error: {$mail->ErrorInfo}");
        
        // Fallback to PHP mail() if SMTP fails (common on DMCA/offshore hosts)
        if ($mail->Mailer == 'smtp') {
            try {
                $fallbackMail = new PHPMailer(true);
                $fallbackMail->isMail();
                $fallbackMail->setFrom($from_email, $from_name);
                $fallbackMail->addAddress($recipient_email);
                $fallbackMail->isHTML(true);
                $fallbackMail->Subject = $subject;
                $fallbackMail->Body    = $html_body;
                $fallbackMail->send();
                return true;
            } catch (Exception $e2) {
                error_log("Fallback Mailer Error: {$fallbackMail->ErrorInfo}");
            }
        }
        return false;
    }
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $tracking_number = trim($_POST['tracking_number'] ?? '');
    $sender_name = trim($_POST['sender_name'] ?? '');
    $sender_phone = trim($_POST['sender_phone'] ?? '');
    $sender_address = trim($_POST['sender_address'] ?? '');
    $receiver_name = trim($_POST['receiver_name'] ?? '');
    $receiver_email = trim($_POST['receiver_email'] ?? '');
    $receiver_phone = trim($_POST['receiver_phone'] ?? '');
    $receiver_address = trim($_POST['receiver_address'] ?? '');
    $service_type = trim($_POST['service_type'] ?? '');
    $weight = trim($_POST['weight'] ?? '');
    $dimensions = trim($_POST['dimensions'] ?? '');
    $package_description = trim($_POST['package_description'] ?? '');
    $estimated_delivery = trim($_POST['estimated_delivery'] ?? '');
    $payment_status = trim($_POST['payment_status'] ?? 'Unpaid');
    $quantity = trim($_POST['quantity'] ?? 1);
    $amount = trim($_POST['amount'] ?? NULL);
    $currency = trim($_POST['currency'] ?? NULL);
    $status = trim($_POST['status'] ?? $_POST['initial_status'] ?? 'Information Received');

    $uploaded_paths = [];
    $files_uploaded = 0;

    if (isset($_FILES['package_images']) && is_array($_FILES['package_images']['name'])) {
        $file_count = count($_FILES['package_images']['name']);
        for ($i = 0; $i < $file_count; $i++) {
            if ($_FILES['package_images']['error'][$i] !== UPLOAD_ERR_OK) { continue; }
            $file_name = $_FILES['package_images']['name'][$i];
            $file_tmp_name = $_FILES['package_images']['tmp_name'][$i];
            $file_type = $_FILES['package_images']['type'][$i];

            $allowed_types = ['image/jpeg', 'image/png'];
            if (!in_array($file_type, $allowed_types)) { continue; }

            $file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
            $new_file_name = $tracking_number . '_' . uniqid() . '.' . $file_ext;
            $target_file = $upload_dir . $new_file_name;
            
            if (move_uploaded_file($file_tmp_name, $target_file)) {
                $files_uploaded++;
                $db_path = str_replace('../', '', $target_file);
                $uploaded_paths[] = $db_path;
            }
        }
    }
    $package_images_csv = !empty($uploaded_paths) ? implode(',', $uploaded_paths) : NULL;

    if (isset($_POST['update_shipment'])) {
        $shipment_id = $_POST['shipment_id'];
        try {
            $pdo->beginTransaction();
            $sql = "UPDATE shipments SET 
                    sender_name = ?, sender_phone = ?, sender_address = ?, 
                    receiver_name = ?, receiver_email = ?, receiver_phone = ?, receiver_address = ?, 
                    service_type = ?, estimated_delivery = ?, payment_status = ?, 
                    amount = ?, currency = ?, quantity = ?, weight = ?, dimensions = ?, 
                    package_description = ?, status = ?" . ($package_images_csv ? ", package_images = ?" : "") . "
                    WHERE id = ?";
            $params = [$sender_name, $sender_phone, $sender_address, $receiver_name, $receiver_email, $receiver_phone, $receiver_address, $service_type, $estimated_delivery, $payment_status, $amount, $currency, $quantity, $weight, $dimensions, $package_description, $status];
            if ($package_images_csv) { $params[] = $package_images_csv; }
            $params[] = $shipment_id;
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $pdo->commit();
            $_SESSION['message'] = "Shipment <strong>#$tracking_number</strong> has been updated successfully!";
            $_SESSION['message_type'] = 'success';
            header("location: shipment_manager.php");
            exit();
        } catch (Exception $e) {
            $pdo->rollBack();
            $_SESSION['message'] = "Critical error during update: " . $e->getMessage();
            $_SESSION['message_type'] = 'danger';
            header("location: edit_shipment.php?id=$shipment_id");
            exit();
        }
    } else {
        // CREATE NEW
        $pdo->beginTransaction();
        try {
            $sql1 = "INSERT INTO shipments (tracking_number, sender_name, sender_address, sender_phone, receiver_name, receiver_address, receiver_email, receiver_phone, package_description, weight, dimensions, service_type, quantity, estimated_delivery, status, package_images, payment_status, amount, currency) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt1 = $pdo->prepare($sql1);
            $stmt1->execute([$tracking_number, $sender_name, $sender_address, $sender_phone, $receiver_name, $receiver_address, $receiver_email, $receiver_phone, $package_description, $weight, $dimensions, $service_type, $quantity, $estimated_delivery, $status, $package_images_csv, $payment_status, $amount, $currency]);
            $shipment_id = $pdo->lastInsertId();
            
            $sql2 = "INSERT INTO tracking_history (shipment_id, location, status_update) VALUES (?, ?, ?)";
            $stmt2 = $pdo->prepare($sql2);
            $stmt2->execute([$shipment_id, $sender_address, $status]);
            $pdo->commit();
            
            $site_settings = get_site_settings($pdo);
            if (!empty($receiver_email)) {
                $shipment_data = [
                    'tracking_number' => $tracking_number,
                    'receiver_name' => $receiver_name,
                    'receiver_address' => $receiver_address,
                    'status' => $status,
                    'estimated_delivery' => $estimated_delivery,
                    'payment_status' => $payment_status,
                    'amount' => $amount,
                    'currency' => $currency,
                    'quantity' => $quantity,
                    'weight' => $weight
                ];
                $smtp_config_missing = false;
                if ($payment_status == 'Unpaid' || $payment_status == 'Collect on Delivery') {
                    $html_body = get_invoice_email_body($shipment_data, $site_settings);
                    $subject = "Invoice for Shipment #" . $tracking_number;
                } else {
                    $html_body = get_tracking_email_body($shipment_data, $site_settings);
                    $subject = "Shipment Confirmed #" . $tracking_number;
                }
                send_email_notification($site_settings, $receiver_email, $subject, $html_body, $smtp_config_missing);
            }

            $_SESSION['message'] = "Shipment created successfully!";
            $_SESSION['message_type'] = 'success';
            header("location: create_shipment.php");
            exit();
        } catch (Exception $e) {
            $pdo->rollBack();
            $_SESSION['message'] = "Error: " . $e->getMessage();
            $_SESSION['message_type'] = 'danger';
            header("location: create_shipment.php");
            exit();
        }
    }
}
?>