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

$id = (int)($_GET['id'] ?? 0);
if (!$id) { header('Location: shipments.php'); exit; }

$shipment = $pdo->prepare('SELECT * FROM shipments WHERE id=?');
$shipment->execute([$id]);
$ship = $shipment->fetch();
if (!$ship) { header('Location: shipments.php'); exit; }

$sender   = $pdo->prepare('SELECT * FROM senders WHERE shipment_id=? LIMIT 1');
$sender->execute([$id]); $snd = $sender->fetch();

$receiver = $pdo->prepare('SELECT * FROM receivers WHERE shipment_id=? LIMIT 1');
$receiver->execute([$id]); $rcv = $receiver->fetch();

$histStmt = $pdo->prepare('SELECT * FROM tracking_history WHERE shipment_id=? ORDER BY sort_order ASC');
$histStmt->execute([$id]); $history = $histStmt->fetchAll();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $t = $_POST;
    try {
        $pdo->beginTransaction();

        $pdo->prepare('UPDATE shipments SET
            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=?,actual_delivery=?,status=?,
            declared_value=?,currency=?,freight_charge=?,insurance_charge=?,handling_charge=?,other_charge=?,
            special_instructions=? WHERE id=?')->execute([
            $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['actual_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,$id,
        ]);

        // Update sender
        $pdo->prepare('UPDATE senders SET full_name=?,company=?,email=?,phone=?,address=?,city=?,state=?,country=?,postal_code=? WHERE shipment_id=?')->execute([
            $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,$id,
        ]);

        // Update receiver
        $pdo->prepare('UPDATE receivers SET full_name=?,company=?,email=?,phone=?,address=?,city=?,state=?,country=?,postal_code=? WHERE shipment_id=?')->execute([
            $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,$id,
        ]);

        // Update tracking history active step
        $statusMap=['order_placed'=>0,'picked_up'=>1,'in_transit'=>2,'out_for_delivery'=>3,'delivered'=>4,'on_hold'=>99,'returned'=>99,'cancelled'=>99];
        $activeStep = $statusMap[$t['status']??'order_placed'] ?? 0;
        foreach ($history as $i=>$h) {
            $isActive = ($h['sort_order']-1 === $activeStep) ? 1 : 0;
            $edate = ($h['sort_order']-1 <= $activeStep && $activeStep < 99) ? ($h['event_date'] ?? date('Y-m-d H:i:s')) : $h['event_date'];
            $pdo->prepare('UPDATE tracking_history SET is_active=?,event_date=? WHERE id=?')->execute([$isActive,$edate,$h['id']]);
        }

        $pdo->commit();
        $success = 'Shipment updated successfully!';
        // Refresh data
        $shipment->execute([$id]); $ship = $shipment->fetch();
        $sender->execute([$id]); $snd = $sender->fetch();
        $receiver->execute([$id]); $rcv = $receiver->fetch();
        $histStmt->execute([$id]); $history = $histStmt->fetchAll();
    } catch (Exception $e) {
        $pdo->rollBack();
        $error = 'Error: ' . htmlspecialchars($e->getMessage());
    }
}

$v = fn($key,$src=null) => htmlspecialchars(($src??$ship)[$key]??'');
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Edit 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-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;">
        <li style="padding:8px 20px;"><a href="dashboard.php" style="color:#ccc;text-decoration:none;">Dashboard</a></li>
        <li style="padding:8px 20px;"><a href="shipments.php" style="color:#FF440A;font-weight:600;text-decoration:none;">Shipments</a></li>
        <li style="padding:8px 20px;"><a href="add-shipment.php" style="color:#ccc;text-decoration:none;">Add Shipment</a></li>
        <li style="padding:8px 20px;"><a href="../track.php" style="color:#ccc;text-decoration:none;" target="_blank">View Website</a></li>
      </ul>
    </nav>
    <div style="margin-left:220px;padding:30px;flex:1;">
      <h3 style="margin-bottom:4px;">Edit Shipment</h3>
      <p style="color:#888;margin-bottom:20px;">Tracking #: <strong><?= $v('tracking_number') ?></strong></p>

      <?php if ($success): ?><div style="background:#d4edda;padding:12px 20px;border-radius:6px;margin-bottom:20px;color:#155724;"><?= $success ?></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">
        <div class="form-section">
          <h5>Status & Dates</h5>
          <div class="row">
            <div class="col-md-3 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 ?>" <?= ($ship['status']===$s)?'selected':'' ?>><?= ucwords(str_replace('_',' ',$s)) ?></option>
                <?php endforeach ?>
              </select>
            </div>
            <div class="col-md-3 form-group"><label>Service</label>
              <select name="service_type" class="form-control">
                <?php foreach(['standard','express','air_freight','ocean_freight','cargo','packaging_storage'] as $s): ?>
                <option value="<?= $s ?>" <?= ($ship['service_type']===$s)?'selected':'' ?>><?= ucwords(str_replace('_',' ',$s)) ?></option>
                <?php endforeach ?>
              </select>
            </div>
            <div class="col-md-3 form-group"><label>Ship Mode</label>
              <select name="shipping_mode" class="form-control">
                <?php foreach(['air','sea','land','multimodal'] as $s): ?>
                <option value="<?= $s ?>" <?= ($ship['shipping_mode']===$s)?'selected':'' ?>><?= ucfirst($s) ?></option>
                <?php endforeach ?>
              </select>
            </div>
            <div class="col-md-3 form-group"><label>Ship Date</label><input type="date" name="ship_date" class="form-control" value="<?= $v('ship_date') ?>"></div>
            <div class="col-md-3 form-group"><label>Est. Delivery</label><input type="date" name="estimated_delivery" class="form-control" value="<?= $v('estimated_delivery') ?>"></div>
            <div class="col-md-3 form-group"><label>Actual Delivery (if delivered)</label><input type="datetime-local" name="actual_delivery" class="form-control" value="<?= $v('actual_delivery') ?>"></div>
          </div>
        </div>

        <div class="form-section">
          <h5>Package</h5>
          <div class="row">
            <div class="col-md-6 form-group"><label>Description</label><input type="text" name="description" class="form-control" value="<?= $v('description') ?>"></div>
            <div class="col-md-2 form-group"><label>Weight</label><input type="number" step="0.01" name="weight" class="form-control" value="<?= $v('weight') ?>"></div>
            <div class="col-md-2 form-group"><label>Unit</label><select name="weight_unit" class="form-control"><option <?= $ship['weight_unit']==='kg'?'selected':'' ?>>kg</option><option <?= $ship['weight_unit']==='lbs'?'selected':'' ?>>lbs</option></select></div>
            <div class="col-md-2 form-group"><label>Qty</label><input type="number" name="quantity" class="form-control" value="<?= $v('quantity') ?>"></div>
            <div class="col-md-3 form-group"><label>Package Type</label><input type="text" name="package_type" class="form-control" value="<?= $v('package_type') ?>"></div>
            <div class="col-md-3 form-group"><label>Dimensions</label><input type="text" name="dimensions" class="form-control" value="<?= $v('dimensions') ?>"></div>
          </div>
        </div>

        <div class="form-section">
          <h5>Origin</h5>
          <div class="row">
            <div class="col-md-5 form-group"><label>Address</label><input type="text" name="origin_address" class="form-control" value="<?= $v('origin_address') ?>"></div>
            <div class="col-md-3 form-group"><label>City</label><input type="text" name="origin_city" class="form-control" value="<?= $v('origin_city') ?>"></div>
            <div class="col-md-2 form-group"><label>State</label><input type="text" name="origin_state" class="form-control" value="<?= $v('origin_state') ?>"></div>
            <div class="col-md-2 form-group"><label>Country</label><input type="text" name="origin_country" class="form-control" value="<?= $v('origin_country') ?>"></div>
          </div>
        </div>

        <div class="form-section">
          <h5>Destination</h5>
          <div class="row">
            <div class="col-md-5 form-group"><label>Address</label><input type="text" name="destination_address" class="form-control" value="<?= $v('destination_address') ?>"></div>
            <div class="col-md-3 form-group"><label>City</label><input type="text" name="destination_city" class="form-control" value="<?= $v('destination_city') ?>"></div>
            <div class="col-md-2 form-group"><label>State</label><input type="text" name="destination_state" class="form-control" value="<?= $v('destination_state') ?>"></div>
            <div class="col-md-2 form-group"><label>Country</label><input type="text" name="destination_country" class="form-control" value="<?= $v('destination_country') ?>"></div>
          </div>
        </div>

        <div class="form-section">
          <h5>Sender</h5>
          <div class="row">
            <div class="col-md-3 form-group"><label>Name</label><input type="text" name="sender_name" class="form-control" value="<?= $v('full_name',$snd) ?>"></div>
            <div class="col-md-3 form-group"><label>Company</label><input type="text" name="sender_company" class="form-control" value="<?= $v('company',$snd) ?>"></div>
            <div class="col-md-3 form-group"><label>Phone</label><input type="text" name="sender_phone" class="form-control" value="<?= $v('phone',$snd) ?>"></div>
            <div class="col-md-3 form-group"><label>Email</label><input type="email" name="sender_email" class="form-control" value="<?= $v('email',$snd) ?>"></div>
            <div class="col-md-4 form-group"><label>Address</label><input type="text" name="sender_address" class="form-control" value="<?= $v('address',$snd) ?>"></div>
            <div class="col-md-2 form-group"><label>City</label><input type="text" name="sender_city" class="form-control" value="<?= $v('city',$snd) ?>"></div>
            <div class="col-md-2 form-group"><label>Country</label><input type="text" name="sender_country" class="form-control" value="<?= $v('country',$snd) ?>"></div>
          </div>
        </div>

        <div class="form-section">
          <h5>Receiver</h5>
          <div class="row">
            <div class="col-md-3 form-group"><label>Name</label><input type="text" name="receiver_name" class="form-control" value="<?= $v('full_name',$rcv) ?>"></div>
            <div class="col-md-3 form-group"><label>Company</label><input type="text" name="receiver_company" class="form-control" value="<?= $v('company',$rcv) ?>"></div>
            <div class="col-md-3 form-group"><label>Phone</label><input type="text" name="receiver_phone" class="form-control" value="<?= $v('phone',$rcv) ?>"></div>
            <div class="col-md-3 form-group"><label>Email</label><input type="email" name="receiver_email" class="form-control" value="<?= $v('email',$rcv) ?>"></div>
            <div class="col-md-4 form-group"><label>Address</label><input type="text" name="receiver_address" class="form-control" value="<?= $v('address',$rcv) ?>"></div>
            <div class="col-md-2 form-group"><label>City</label><input type="text" name="receiver_city" class="form-control" value="<?= $v('city',$rcv) ?>"></div>
            <div class="col-md-2 form-group"><label>Country</label><input type="text" name="receiver_country" class="form-control" value="<?= $v('country',$rcv) ?>"></div>
          </div>
        </div>

        <div class="form-section">
          <h5>Charges</h5>
          <div class="row">
            <div class="col-md-2 form-group"><label>Currency</label><select name="currency" class="form-control"><?php foreach(['NGN','USD','GBP','EUR','AED'] as $c): ?><option <?= $ship['currency']===$c?'selected':'' ?>><?= $c ?></option><?php endforeach ?></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="<?= $v('freight_charge') ?>"></div>
            <div class="col-md-2 form-group"><label>Insurance</label><input type="number" step="0.01" name="insurance_charge" class="form-control" value="<?= $v('insurance_charge') ?>"></div>
            <div class="col-md-2 form-group"><label>Handling</label><input type="number" step="0.01" name="handling_charge" class="form-control" value="<?= $v('handling_charge') ?>"></div>
            <div class="col-md-2 form-group"><label>Other</label><input type="number" step="0.01" name="other_charge" class="form-control" value="<?= $v('other_charge') ?>"></div>
          </div>
          <div class="form-group"><label>Special Instructions</label><textarea name="special_instructions" class="form-control" rows="2"><?= $v('special_instructions') ?></textarea></div>
        </div>

        <button type="submit" class="btn-submit">Save Changes</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>
