<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_login();

$success = '';
$error   = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $t = $_POST;

    // Generate tracking number if blank
    if (empty(trim($t['tracking_number']))) {
        $year = date('Y');
        $last = $pdo->query("SELECT id FROM shipments ORDER BY id DESC LIMIT 1")->fetchColumn();
        $t['tracking_number'] = 'TEC-' . $year . '-' . str_pad(($last + 1), 4, '0', STR_PAD_LEFT);
    }

    try {
        $pdo->beginTransaction();

        // Insert shipment
        $stmt = $pdo->prepare('INSERT INTO shipments
            (tracking_number,barcode,description,weight,weight_unit,quantity,package_type,dimensions,
             service_type,shipping_mode,
             origin_address,origin_city,origin_state,origin_country,
             destination_address,destination_city,destination_state,destination_country,
             ship_date,estimated_delivery,status,
             declared_value,currency,freight_charge,insurance_charge,handling_charge,other_charge,
             special_instructions,created_by)
            VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
        $stmt->execute([
            strtoupper(trim($t['tracking_number'])),
            strtoupper(trim($t['tracking_number'])),
            $t['description'] ?? null,
            $t['weight'] ?: null,
            $t['weight_unit'] ?? 'kg',
            $t['quantity'] ?: 1,
            $t['package_type'] ?? null,
            $t['dimensions'] ?? null,
            $t['service_type'] ?? 'standard',
            $t['shipping_mode'] ?? 'air',
            $t['origin_address'] ?? '',
            $t['origin_city'] ?? '',
            $t['origin_state'] ?? null,
            $t['origin_country'] ?? '',
            $t['destination_address'] ?? '',
            $t['destination_city'] ?? '',
            $t['destination_state'] ?? null,
            $t['destination_country'] ?? '',
            $t['ship_date'] ?? date('Y-m-d'),
            $t['estimated_delivery'] ?: null,
            $t['status'] ?? 'order_placed',
            $t['declared_value'] ?: null,
            $t['currency'] ?? 'NGN',
            $t['freight_charge'] ?: 0,
            $t['insurance_charge'] ?: 0,
            $t['handling_charge'] ?: 0,
            $t['other_charge'] ?: 0,
            $t['special_instructions'] ?? null,
            $_SESSION['admin_id'],
        ]);
        $shipment_id = $pdo->lastInsertId();

        // Insert sender
        $pdo->prepare('INSERT INTO senders(shipment_id,full_name,company,email,phone,address,city,state,country,postal_code)VALUES(?,?,?,?,?,?,?,?,?,?)')->execute([
            $shipment_id,$t['sender_name'],$t['sender_company']??null,$t['sender_email']??null,
            $t['sender_phone']??'',$t['sender_address']??'',$t['sender_city']??'',$t['sender_state']??null,$t['sender_country']??'',$t['sender_postal']??null,
        ]);

        // Insert receiver
        $pdo->prepare('INSERT INTO receivers(shipment_id,full_name,company,email,phone,address,city,state,country,postal_code)VALUES(?,?,?,?,?,?,?,?,?,?)')->execute([
            $shipment_id,$t['receiver_name'],$t['receiver_company']??null,$t['receiver_email']??null,
            $t['receiver_phone']??'',$t['receiver_address']??'',$t['receiver_city']??'',$t['receiver_state']??null,$t['receiver_country']??'',$t['receiver_postal']??null,
        ]);

        // Insert initial tracking history
        $statuses = [
            ['Order Placed','Shipment booked and confirmed',1],
            ['Picked Up','Package collected from sender',0],
            ['In Transit','Shipment in transit',0],
            ['Out for Delivery','Package out for delivery',0],
            ['Delivered','Delivered successfully',0],
        ];
        $insertH = $pdo->prepare('INSERT INTO tracking_history(shipment_id,status,note,location,event_date,is_active,sort_order)VALUES(?,?,?,?,?,?,?)');
        $currentStatus = $t['status'] ?? 'order_placed';
        $statusMap = ['order_placed'=>0,'picked_up'=>1,'in_transit'=>2,'out_for_delivery'=>3,'delivered'=>4];
        $activeStep = $statusMap[$currentStatus] ?? 0;
        foreach ($statuses as $i=>[$sname,$snote,$_]) {
            $isActive = ($i === $activeStep) ? 1 : 0;
            $edate = ($i <= $activeStep) ? date('Y-m-d H:i:s') : null;
            $insertH->execute([$shipment_id,$sname,$snote,$t['origin_city']??'',$edate,$isActive,$i+1]);
        }

        $pdo->commit();
        $success = 'Shipment <strong>' . htmlspecialchars(strtoupper(trim($t['tracking_number']))) . '</strong> created successfully!';
    } catch (Exception $e) {
        $pdo->rollBack();
        $error = 'Error creating shipment: ' . htmlspecialchars($e->getMessage());
    }
}

$navLink = fn($href,$label,$active=false) => '<li style="padding:8px 20px;"><a href="'.$href.'" style="color:'.($active?'#FF440A':'#ccc').';text-decoration:none;'.($active?'font-weight:600;':'').'">'.$label.'</a></li>';
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Add Shipment | Turi Express Admin</title>
  <link rel="stylesheet" href="vendors/mdi/css/materialdesignicons.min.css">
  <link rel="stylesheet" href="vendors/base/vendor.bundle.base.css">
  <link rel="stylesheet" href="css/style.css">
  <link rel="shortcut icon" href="images/favicon.png">
  <style>
    .form-section{background:#fff;border-radius:8px;padding:24px;margin-bottom:20px;box-shadow:0 2px 8px rgba(0,0,0,.07)}
    .form-section h5{font-weight:700;border-bottom:2px solid #FF440A;padding-bottom:8px;margin-bottom:20px}
    .form-group label{font-weight:600;font-size:13px}
    .form-control{border:1px solid #ddd;border-radius:4px;padding:8px 12px}
    .btn-submit{background:#FF440A;color:#fff;border:none;padding:12px 30px;border-radius:4px;font-size:15px;cursor:pointer;font-weight:600}
  </style>
</head>
<body>
<div class="container-scroller">
  <nav style="background:#FF440A;padding:0 20px;position:fixed;top:0;width:100%;z-index:999;display:flex;align-items:center;justify-content:space-between;height:56px;">
    <a href="dashboard.php" style="color:#fff;font-weight:700;font-size:18px;text-decoration:none;">Turi Express Admin</a>
    <div><span style="color:#fff;margin-right:16px;"><?= htmlspecialchars($_SESSION['admin_name']) ?></span><a href="logout.php" style="color:#fff;border:1px solid #fff;padding:5px 12px;border-radius:4px;font-size:13px;text-decoration:none;">Logout</a></div>
  </nav>
  <div style="display:flex;padding-top:56px;">
    <nav style="background:#2c2c2c;min-height:100vh;width:220px;position:fixed;padding-top:20px;">
      <ul style="list-style:none;padding:0;">
        <?= $navLink('dashboard.php','Dashboard') ?>
        <?= $navLink('shipments.php','Shipments') ?>
        <?= $navLink('add-shipment.php','Add Shipment',true) ?>
        <?= $navLink('../track.php','View Website') ?>
      </ul>
    </nav>
    <div style="margin-left:220px;padding:30px;flex:1;">
      <h3 style="margin-bottom:24px;">Add New Shipment</h3>

      <?php if ($success): ?><div style="background:#d4edda;padding:12px 20px;border-radius:6px;margin-bottom:20px;color:#155724;"><?= $success ?> <a href="shipments.php">View all shipments</a></div><?php endif ?>
      <?php if ($error): ?><div style="background:#f8d7da;padding:12px 20px;border-radius:6px;margin-bottom:20px;color:#721c24;"><?= $error ?></div><?php endif ?>

      <form method="POST">
        <!-- Tracking -->
        <div class="form-section">
          <h5>Tracking Details</h5>
          <div class="row">
            <div class="col-md-4 form-group">
              <label>Tracking Number <small style="color:#888;">(leave blank to auto-generate)</small></label>
              <input type="text" name="tracking_number" class="form-control" placeholder="e.g. TEC-2024-0005" value="<?= htmlspecialchars($_POST['tracking_number'] ?? '') ?>">
            </div>
            <div class="col-md-4 form-group">
              <label>Status *</label>
              <select name="status" class="form-control">
                <?php foreach(['order_placed','picked_up','in_transit','out_for_delivery','delivered','on_hold','returned','cancelled'] as $s): ?>
                <option value="<?= $s ?>" <?= (($_POST['status']??'order_placed')===$s)?'selected':'' ?>><?= ucwords(str_replace('_',' ',$s)) ?></option>
                <?php endforeach ?>
              </select>
            </div>
            <div class="col-md-4 form-group">
              <label>Ship Date *</label>
              <input type="date" name="ship_date" class="form-control" value="<?= htmlspecialchars($_POST['ship_date'] ?? date('Y-m-d')) ?>">
            </div>
            <div class="col-md-4 form-group">
              <label>Estimated Delivery</label>
              <input type="date" name="estimated_delivery" class="form-control" value="<?= htmlspecialchars($_POST['estimated_delivery'] ?? '') ?>">
            </div>
            <div class="col-md-4 form-group">
              <label>Service Type</label>
              <select name="service_type" class="form-control">
                <?php foreach(['standard','express','air_freight','ocean_freight','cargo','packaging_storage'] as $s): ?>
                <option value="<?= $s ?>" <?= (($_POST['service_type']??'')===$s)?'selected':'' ?>><?= ucwords(str_replace('_',' ',$s)) ?></option>
                <?php endforeach ?>
              </select>
            </div>
            <div class="col-md-4 form-group">
              <label>Shipping Mode</label>
              <select name="shipping_mode" class="form-control">
                <?php foreach(['air','sea','land','multimodal'] as $s): ?>
                <option value="<?= $s ?>" <?= (($_POST['shipping_mode']??'air')===$s)?'selected':'' ?>><?= ucfirst($s) ?></option>
                <?php endforeach ?>
              </select>
            </div>
          </div>
        </div>

        <!-- Package -->
        <div class="form-section">
          <h5>Package Details</h5>
          <div class="row">
            <div class="col-md-6 form-group"><label>Description</label><input type="text" name="description" class="form-control" value="<?= htmlspecialchars($_POST['description'] ?? '') ?>"></div>
            <div class="col-md-3 form-group"><label>Weight</label><input type="number" step="0.01" name="weight" class="form-control" value="<?= htmlspecialchars($_POST['weight'] ?? '') ?>"></div>
            <div class="col-md-3 form-group"><label>Unit</label><select name="weight_unit" class="form-control"><option value="kg">kg</option><option value="lbs">lbs</option></select></div>
            <div class="col-md-3 form-group"><label>Quantity</label><input type="number" name="quantity" class="form-control" value="<?= htmlspecialchars($_POST['quantity'] ?? '1') ?>"></div>
            <div class="col-md-3 form-group"><label>Package Type</label><input type="text" name="package_type" class="form-control" placeholder="Box, Pallet, Envelope..." value="<?= htmlspecialchars($_POST['package_type'] ?? '') ?>"></div>
            <div class="col-md-6 form-group"><label>Dimensions</label><input type="text" name="dimensions" class="form-control" placeholder="e.g. 40x30x20 cm" value="<?= htmlspecialchars($_POST['dimensions'] ?? '') ?>"></div>
          </div>
        </div>

        <!-- Origin -->
        <div class="form-section">
          <h5>Origin (Sender Location)</h5>
          <div class="row">
            <div class="col-md-6 form-group"><label>Address *</label><input type="text" name="origin_address" class="form-control" required value="<?= htmlspecialchars($_POST['origin_address'] ?? '') ?>"></div>
            <div class="col-md-3 form-group"><label>City *</label><input type="text" name="origin_city" class="form-control" required value="<?= htmlspecialchars($_POST['origin_city'] ?? '') ?>"></div>
            <div class="col-md-3 form-group"><label>State/Province</label><input type="text" name="origin_state" class="form-control" value="<?= htmlspecialchars($_POST['origin_state'] ?? '') ?>"></div>
            <div class="col-md-3 form-group"><label>Country *</label><input type="text" name="origin_country" class="form-control" required value="<?= htmlspecialchars($_POST['origin_country'] ?? '') ?>"></div>
          </div>
        </div>

        <!-- Destination -->
        <div class="form-section">
          <h5>Destination (Receiver Location)</h5>
          <div class="row">
            <div class="col-md-6 form-group"><label>Address *</label><input type="text" name="destination_address" class="form-control" required value="<?= htmlspecialchars($_POST['destination_address'] ?? '') ?>"></div>
            <div class="col-md-3 form-group"><label>City *</label><input type="text" name="destination_city" class="form-control" required value="<?= htmlspecialchars($_POST['destination_city'] ?? '') ?>"></div>
            <div class="col-md-3 form-group"><label>State/Province</label><input type="text" name="destination_state" class="form-control" value="<?= htmlspecialchars($_POST['destination_state'] ?? '') ?>"></div>
            <div class="col-md-3 form-group"><label>Country *</label><input type="text" name="destination_country" class="form-control" required value="<?= htmlspecialchars($_POST['destination_country'] ?? '') ?>"></div>
          </div>
        </div>

        <!-- Sender -->
        <div class="form-section">
          <h5>Sender Information</h5>
          <div class="row">
            <div class="col-md-4 form-group"><label>Full Name *</label><input type="text" name="sender_name" class="form-control" required value="<?= htmlspecialchars($_POST['sender_name'] ?? '') ?>"></div>
            <div class="col-md-4 form-group"><label>Company</label><input type="text" name="sender_company" class="form-control" value="<?= htmlspecialchars($_POST['sender_company'] ?? '') ?>"></div>
            <div class="col-md-4 form-group"><label>Phone *</label><input type="text" name="sender_phone" class="form-control" required value="<?= htmlspecialchars($_POST['sender_phone'] ?? '') ?>"></div>
            <div class="col-md-4 form-group"><label>Email</label><input type="email" name="sender_email" class="form-control" value="<?= htmlspecialchars($_POST['sender_email'] ?? '') ?>"></div>
            <div class="col-md-4 form-group"><label>Address</label><input type="text" name="sender_address" class="form-control" value="<?= htmlspecialchars($_POST['sender_address'] ?? '') ?>"></div>
            <div class="col-md-2 form-group"><label>City</label><input type="text" name="sender_city" class="form-control" value="<?= htmlspecialchars($_POST['sender_city'] ?? '') ?>"></div>
            <div class="col-md-2 form-group"><label>Country</label><input type="text" name="sender_country" class="form-control" value="<?= htmlspecialchars($_POST['sender_country'] ?? '') ?>"></div>
          </div>
        </div>

        <!-- Receiver -->
        <div class="form-section">
          <h5>Receiver Information</h5>
          <div class="row">
            <div class="col-md-4 form-group"><label>Full Name *</label><input type="text" name="receiver_name" class="form-control" required value="<?= htmlspecialchars($_POST['receiver_name'] ?? '') ?>"></div>
            <div class="col-md-4 form-group"><label>Company</label><input type="text" name="receiver_company" class="form-control" value="<?= htmlspecialchars($_POST['receiver_company'] ?? '') ?>"></div>
            <div class="col-md-4 form-group"><label>Phone *</label><input type="text" name="receiver_phone" class="form-control" required value="<?= htmlspecialchars($_POST['receiver_phone'] ?? '') ?>"></div>
            <div class="col-md-4 form-group"><label>Email</label><input type="email" name="receiver_email" class="form-control" value="<?= htmlspecialchars($_POST['receiver_email'] ?? '') ?>"></div>
            <div class="col-md-4 form-group"><label>Address</label><input type="text" name="receiver_address" class="form-control" value="<?= htmlspecialchars($_POST['receiver_address'] ?? '') ?>"></div>
            <div class="col-md-2 form-group"><label>City</label><input type="text" name="receiver_city" class="form-control" value="<?= htmlspecialchars($_POST['receiver_city'] ?? '') ?>"></div>
            <div class="col-md-2 form-group"><label>Country</label><input type="text" name="receiver_country" class="form-control" value="<?= htmlspecialchars($_POST['receiver_country'] ?? '') ?>"></div>
          </div>
        </div>

        <!-- Charges -->
        <div class="form-section">
          <h5>Charges (<?= htmlspecialchars($_POST['currency'] ?? 'NGN') ?>)</h5>
          <div class="row">
            <div class="col-md-2 form-group"><label>Currency</label><select name="currency" class="form-control"><option>NGN</option><option>USD</option><option>GBP</option><option>EUR</option><option>AED</option></select></div>
            <div class="col-md-2 form-group"><label>Freight</label><input type="number" step="0.01" name="freight_charge" class="form-control" value="<?= htmlspecialchars($_POST['freight_charge'] ?? '0') ?>"></div>
            <div class="col-md-2 form-group"><label>Insurance</label><input type="number" step="0.01" name="insurance_charge" class="form-control" value="<?= htmlspecialchars($_POST['insurance_charge'] ?? '0') ?>"></div>
            <div class="col-md-2 form-group"><label>Handling</label><input type="number" step="0.01" name="handling_charge" class="form-control" value="<?= htmlspecialchars($_POST['handling_charge'] ?? '0') ?>"></div>
            <div class="col-md-2 form-group"><label>Other</label><input type="number" step="0.01" name="other_charge" class="form-control" value="<?= htmlspecialchars($_POST['other_charge'] ?? '0') ?>"></div>
          </div>
          <div class="form-group"><label>Special Instructions</label><textarea name="special_instructions" class="form-control" rows="2"><?= htmlspecialchars($_POST['special_instructions'] ?? '') ?></textarea></div>
        </div>

        <button type="submit" class="btn-submit">Create Shipment</button>
        <a href="shipments.php" style="margin-left:16px;color:#888;">Cancel</a>
      </form>
    </div>
  </div>
</div>
<script src="vendors/base/vendor.bundle.base.js"></script>
</body>
</html>
