<?php

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/csrf.php';
require_once __DIR__ . '/../app/docno.php';
require_once __DIR__ . '/../app/upload.php';

$me = require_role(['ADMIN','DISTRIBUTOR','WAREHOUSE']);
$pdo = db();

function fetch_distributors(PDO $pdo): array {
  return $pdo->query("SELECT id, name FROM distributors WHERE active=1 ORDER BY name")->fetchAll();
}
function fetch_outlets(PDO $pdo): array {
  return $pdo->query("SELECT id, name, default_deal_type FROM outlets WHERE active=1 ORDER BY name")->fetchAll();
}
function fetch_issues(PDO $pdo): array {
  return $pdo->query("
    SELECT i.id, CONCAT(p.name,' - ',LPAD(i.issue_month,2,'0'),'/',i.issue_year) AS label, i.cover_price
    FROM issues i JOIN products p ON p.id=i.product_id
    WHERE i.status='OPEN'
    ORDER BY i.issue_year DESC, i.issue_month DESC, p.name
  ")->fetchAll();
}
function fetch_delivery(PDO $pdo, int $id): ?array {
  $st = $pdo->prepare("
    SELECT od.*,
           u1.name AS created_by_name,
           u2.name AS manager_by_name,
           dist.name AS distributor_name,
           o.name AS outlet_name
    FROM outlet_deliveries od
    JOIN users u1 ON u1.id = od.created_by
    LEFT JOIN users u2 ON u2.id = od.manager_by
    JOIN distributors dist ON dist.id = od.distributor_id
    JOIN outlets o ON o.id = od.outlet_id
    WHERE od.id=?
  ");
  $st->execute([$id]);
  $r = $st->fetch();
  return $r ?: null;
}
function fetch_delivery_items(PDO $pdo, int $deliveryId): array {
  $st = $pdo->prepare("
    SELECT odi.*, CONCAT(p.name,' - ',LPAD(i.issue_month,2,'0'),'/',i.issue_year) AS issue_label
    FROM outlet_delivery_items odi
    JOIN issues i ON i.id=odi.issue_id
    JOIN products p ON p.id=i.product_id
    WHERE odi.delivery_id=?
    ORDER BY issue_label
  ");
  $st->execute([$deliveryId]);
  return $st->fetchAll();
}
function resolve_unit_price(PDO $pdo, int $outletId, int $issueId, string $deliveryAt): float {
  $st = $pdo->prepare("
    SELECT price_mode, value FROM outlet_issue_pricing
    WHERE outlet_id=? AND issue_id=?
      AND (valid_from IS NULL OR valid_from <= DATE(?))
      AND (valid_to IS NULL OR valid_to >= DATE(?))
    ORDER BY COALESCE(valid_from,'1900-01-01') DESC, id DESC LIMIT 1
  ");
  $st->execute([$outletId, $issueId, $deliveryAt, $deliveryAt]);
  $rule = $st->fetch();
  $st2 = $pdo->prepare("SELECT cover_price FROM issues WHERE id=?");
  $st2->execute([$issueId]);
  $issue = $st2->fetch();
  $cover = $issue ? (float)$issue['cover_price'] : 0.0;
  if (!$rule) return $cover;
  $mode = $rule['price_mode'];
  $val = $rule['value'] !== null ? (float)$rule['value'] : null;
  if ($mode === 'SUPPLY_PRICE' && $val !== null) return $val;
  if ($mode === 'DISCOUNT_PERCENT' && $val !== null) {
    return round($cover * (1.0 - max(0.0, min(100.0, $val)) / 100.0), 3);
  }
  return $cover;
}

/* ── ترجمة الحالة ── */
function odl_status_ar(string $s): array {
  return match($s) {
    'DRAFT'     => ['مسودة',  'badge-draft'],
    'SUBMITTED' => ['مرسلة',  'badge-submitted'],
    'APPROVED'  => ['معتمدة', 'badge-approved'],
    'REJECTED'  => ['مرفوضة','badge-rejected'],
    default     => [$s,        'badge-draft'],
  };
}
function deal_ar(string $d): array {
  return match($d) {
    'CONSIGNMENT' => ['أمانة',      'deal-consign'],
    'DIRECT_SALE' => ['بيع مباشر',  'deal-direct'],
    'FREE'        => ['مجانية',     'deal-free'],
    default       => [$d,            'deal-consign'],
  };
}

$csrf   = csrf_token();
$action = $_GET['action'] ?? 'list';
$id     = (int)($_GET['id'] ?? 0);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $op = $_POST['op'] ?? '';
  $forcedDistributorId = null;
  if ($me['role'] === 'DISTRIBUTOR') {
    if (empty($me['distributor_id'])) exit("Distributor user not linked to distributor_id");
    $forcedDistributorId = (int)$me['distributor_id'];
  }

  if ($op === 'create') {
    $distributor_id = (int)($_POST['distributor_id'] ?? 0);
    $outlet_id      = (int)($_POST['outlet_id']      ?? 0);
    $delivery_at    = trim($_POST['delivery_at']      ?? '');
    $deal_type      = $_POST['deal_type']             ?? 'CONSIGNMENT';
    if ($forcedDistributorId !== null) $distributor_id = $forcedDistributorId;
    if ($distributor_id<=0 || $outlet_id<=0 || $delivery_at==='') exit("Bad data");
    if (!in_array($deal_type, ['CONSIGNMENT','DIRECT_SALE','FREE'], true)) exit("Bad deal type");
    $st = $pdo->prepare("INSERT INTO outlet_deliveries (delivery_no, distributor_id, outlet_id, delivery_at, deal_type, created_by, status) VALUES (NULL, ?, ?, ?, ?, ?, 'DRAFT')");
    $st->execute([$distributor_id, $outlet_id, $delivery_at, $deal_type, (int)$me['id']]);
    redirect("outlet_deliveries.php?action=edit&id=".(int)$pdo->lastInsertId());
  }

  if ($op === 'add_item') {
    $delivery_id = (int)($_POST['delivery_id'] ?? 0);
    $issue_id    = (int)($_POST['issue_id']    ?? 0);
    $qty         = (int)($_POST['qty']          ?? 0);
    if ($delivery_id<=0 || $issue_id<=0 || $qty<=0) exit("Bad item");
    $d = fetch_delivery($pdo, $delivery_id);
    if (!$d) exit("Delivery not found");
    if ($me['role'] === 'DISTRIBUTOR' && (int)$d['distributor_id'] !== (int)$me['distributor_id']) exit("Forbidden");
    if (!in_array($d['status'], ['DRAFT','REJECTED'], true)) exit("Cannot edit in this status");
    $unitPrice = $d['deal_type'] === 'DIRECT_SALE' ? resolve_unit_price($pdo, (int)$d['outlet_id'], $issue_id, $d['delivery_at']) : null;
    $pdo->prepare("INSERT INTO outlet_delivery_items (delivery_id, issue_id, qty_delivered, unit_price_applied) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE qty_delivered = qty_delivered + VALUES(qty_delivered), unit_price_applied = COALESCE(unit_price_applied, VALUES(unit_price_applied))")->execute([$delivery_id, $issue_id, $qty, $unitPrice]);
    redirect("outlet_deliveries.php?action=edit&id=".$delivery_id);
  }

  if ($op === 'remove_item') {
    $delivery_id = (int)($_POST['delivery_id'] ?? 0);
    $item_id     = (int)($_POST['item_id']     ?? 0);
    $d = fetch_delivery($pdo, $delivery_id);
    if (!$d) exit("Delivery not found");
    if ($me['role'] === 'DISTRIBUTOR' && (int)$d['distributor_id'] !== (int)$me['distributor_id']) exit("Forbidden");
    if (!in_array($d['status'], ['DRAFT','REJECTED'], true)) exit("Cannot edit in this status");
    $pdo->prepare("DELETE FROM outlet_delivery_items WHERE id=? AND delivery_id=?")->execute([$item_id, $delivery_id]);
    redirect("outlet_deliveries.php?action=edit&id=".$delivery_id);
  }

  if ($op === 'upload_pod') {
    $delivery_id = (int)($_POST['delivery_id'] ?? 0);
    $d = fetch_delivery($pdo, $delivery_id);
    if (!$d) exit("Delivery not found");
    if ($me['role'] === 'DISTRIBUTOR' && (int)$d['distributor_id'] !== (int)$me['distributor_id']) exit("Forbidden");
    if (!in_array($d['status'], ['DRAFT','REJECTED','SUBMITTED'], true)) exit("Cannot upload in this status");
    if (empty($_FILES['pod']) || !is_array($_FILES['pod'])) exit("No file");
    $attId = save_upload($_FILES['pod'], (int)$me['id']);
    $pdo->prepare("UPDATE outlet_deliveries SET pod_attachment_id=? WHERE id=?")->execute([$attId, $delivery_id]);
    redirect("outlet_deliveries.php?action=edit&id=".$delivery_id);
  }

  if ($op === 'submit') {
    $delivery_id = (int)($_POST['delivery_id'] ?? 0);
    $d = fetch_delivery($pdo, $delivery_id);
    if (!$d) exit("Delivery not found");
    if ($me['role'] === 'DISTRIBUTOR' && (int)$d['distributor_id'] !== (int)$me['distributor_id']) exit("Forbidden");
    if (!in_array($d['status'], ['DRAFT','REJECTED'], true)) exit("Bad status");
    $cnt = $pdo->prepare("SELECT COUNT(*) c FROM outlet_delivery_items WHERE delivery_id=?");
    $cnt->execute([$delivery_id]);
    if ((int)$cnt->fetch()['c'] <= 0) exit("Add items first");
    if (empty($d['delivery_no'])) {
      $no = next_doc_no('ODL', new DateTimeImmutable($d['delivery_at']));
      $pdo->prepare("UPDATE outlet_deliveries SET delivery_no=? WHERE id=?")->execute([$no, $delivery_id]);
    }
    $pdo->prepare("UPDATE outlet_deliveries SET status='SUBMITTED' WHERE id=?")->execute([$delivery_id]);
    redirect("outlet_deliveries.php?action=edit&id=".$delivery_id);
  }

  if ($op === 'approve') {
    require_role(['ADMIN']);
    $delivery_id = (int)($_POST['delivery_id'] ?? 0);
    $d = fetch_delivery($pdo, $delivery_id);
    if (!$d) exit("Delivery not found");
    if ($d['status'] !== 'SUBMITTED') exit("Only SUBMITTED can be approved");
    $pdo->beginTransaction();
    try {
      $pdo->prepare("UPDATE outlet_deliveries SET status='APPROVED', manager_by=?, manager_at=NOW(), manager_reason=NULL WHERE id=?")->execute([(int)$me['id'], $delivery_id]);
      $newInvoiceId = null;
      if ($d['deal_type'] === 'DIRECT_SALE') {
        $invNo = next_doc_no('INV', new DateTimeImmutable($d['delivery_at']));
        $stInv = $pdo->prepare("INSERT INTO invoices (invoice_no, outlet_id, distributor_id, source_type, source_id, issued_at, status, currency, total_amount, total_paid, balance_due, created_by) VALUES (?, ?, ?, 'DIRECT_SALE', ?, ?, 'ISSUED', 'OMR', 0, 0, 0, ?)");
        $stInv->execute([$invNo, (int)$d['outlet_id'], (int)$d['distributor_id'], $delivery_id, $d['delivery_at'], (int)$me['id']]);
        $newInvoiceId = (int)$pdo->lastInsertId();
        $it = $pdo->prepare("SELECT issue_id, qty_delivered, unit_price_applied FROM outlet_delivery_items WHERE delivery_id=?");
        $it->execute([$delivery_id]);
        $total = 0.0;
        foreach ($it->fetchAll() as $row) {
          $qty = (int)$row['qty_delivered'];
          $price = $row['unit_price_applied'] !== null ? (float)$row['unit_price_applied'] : 0.0;
          $line = round($qty * $price, 3);
          $total += $line;
          $pdo->prepare("INSERT INTO invoice_items (invoice_id, issue_id, qty, unit_price, line_total) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE qty = qty + VALUES(qty), line_total = line_total + VALUES(line_total)")->execute([$newInvoiceId, (int)$row['issue_id'], $qty, $price, $line]);
        }
        $total = round($total, 3);
        $pdo->prepare("UPDATE invoices SET total_amount=?, balance_due=? WHERE id=?")->execute([$total, $total, $newInvoiceId]);
      }
      $pdo->commit();
      redirect($newInvoiceId ? "invoices.php?action=view&id=".$newInvoiceId : "outlet_deliveries.php?action=edit&id=".$delivery_id);
    } catch (Throwable $e) { $pdo->rollBack(); throw $e; }
  }

  if ($op === 'reject') {
    require_role(['ADMIN']);
    $delivery_id = (int)($_POST['delivery_id'] ?? 0);
    $reason      = trim($_POST['reason'] ?? '');
    if ($reason === '') exit("Reason required");
    $d = fetch_delivery($pdo, $delivery_id);
    if (!$d) exit("Delivery not found");
    if ($d['status'] !== 'SUBMITTED') exit("Only SUBMITTED can be rejected");
    $pdo->prepare("UPDATE outlet_deliveries SET status='
REJECTED', manager_by=?, manager_at=NOW(), manager_reason=? WHERE id=?")->execute([(int)$me['id'], $reason, $delivery_id]);
    redirect("outlet_deliveries.php?action=edit&id=".$delivery_id);
  }
}

if ($action === 'edit' && $id > 0) {
  $delivery = fetch_delivery($pdo, $id);
  if (!$delivery) { http_response_code(404); exit("Not found"); }
  if ($me['role'] === 'DISTRIBUTOR' && (int)$delivery['distributor_id'] !== (int)$me['distributor_id']) {
    http_response_code(403); exit("Forbidden");
  }
  $items  = fetch_delivery_items($pdo, $id);
  $issues = fetch_issues($pdo);
} else {
  $delivery = null; $items = []; $issues = [];
  if ($me['role'] === 'DISTRIBUTOR') {
    $st = $pdo->prepare("
      SELECT od.id, od.delivery_no, od.delivery_at, od.status, od.deal_type,
             dist.name AS distributor_name, o.name AS outlet_name, u.name AS created_by_name
      FROM outlet_deliveries od
      JOIN distributors dist ON dist.id=od.distributor_id
      JOIN outlets o ON o.id=od.outlet_id
      JOIN users u ON u.id=od.created_by
      WHERE od.distributor_id=? ORDER BY od.id DESC LIMIT 200
    ");
    $st->execute([(int)$me['distributor_id']]);
    $rows = $st->fetchAll();
  } else {
    $rows = $pdo->query("
      SELECT od.id, od.delivery_no, od.delivery_at, od.status, od.deal_type,
             dist.name AS distributor_name, o.name AS outlet_name, u.name AS created_by_name
      FROM outlet_deliveries od
      JOIN distributors dist ON dist.id=od.distributor_id
      JOIN outlets o ON o.id=od.outlet_id
      JOIN users u ON u.id=od.created_by
      ORDER BY od.id DESC LIMIT 200
    ")->fetchAll();
  }
  $distributors = fetch_distributors($pdo);
  $outlets      = fetch_outlets($pdo);
}

$csrf = csrf_token();
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>شحن للمنافذ (ODL) — MGZ</title>
<style>
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  body { font-family: 'Segoe UI', Tahoma, Arial, sans-serif; background: #f3f4f6; color: #1f2937; min-height: 100vh; }

  .back-link { display: inline-block; padding: 10px 20px; color: #6b7280; text-decoration: none; font-size: .9rem; transition: color .2s; }
  .back-link:hover { color: #1d4ed8; }

  .page-header {
    background: linear-gradient(135deg, #1e3a5f 0%, #2563eb 100%);
    color: #fff; padding: 22px 32px; border-radius: 12px;
    margin: 0 20px 24px; display: flex; align-items: center;
    justify-content: space-between; box-shadow: 0 4px 15px rgba(37,99,235,.35);
  }
  .page-header h1 { font-size: 1.5rem; font-weight: 700; }
  .page-header .subtitle { font-size: .85rem; opacity: .8; margin-top: 4px; }
  .page-header .doc-badge { background: rgba(255,255,255,.18); border-radius: 8px; padding: 6px 18px; font-size: .95rem; font-weight: 700; }

  .content { padding: 0 20px 40px; }

  .meta-bar { background: #fff; border-radius: 10px; padding: 16px 24px; margin-bottom: 20px; box-shadow: 0 2px 8px rgba(0,0,0,.07); display: flex; flex-wrap: wrap; gap: 28px; align-items: center; }
  .meta-item { display: flex; flex-direction: column; gap: 3px; }
  .meta-label { font-size: .72rem; color: #9ca3af; text-transform: uppercase; letter-spacing: .6px; }
  .meta-value { font-size: .95rem; font-weight: 600; color: #1e3a5f; }

  .alert-danger { background: #fef2f2; border: 1px solid #fca5a5; border-radius: 8px; padding: 14px 20px; color: #991b1b; margin-bottom: 20px; display: flex; gap: 10px; align-items: flex-start; font-size: .92rem; }

  .card { background: #fff; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,.08); margin-bottom: 24px; overflow: hidden; }
  .card-header { padding: 15px 24px; border-bottom: 1px solid #e5e7eb; font-size: 1rem; font-weight: 600; color: #1e3a5f; display: flex; align-items: center; gap: 8px; }
  .card-body { padding: 24px; }

  .form-row { display: flex; align-items: flex-end; gap: 14px; flex-wrap: wrap; }
  .form-row label { display: flex; flex-direction: column; gap: 5px; font-size: .82rem; color: #374151; font-weight: 500; }
  .form-row input, .form-row select { padding: 9px 14px; border: 1px solid #d1d5db; border-radius: 7px; font-size: .92rem; font-family: inherit; background: #f9fafb; color: #1f2937; outline: none; transition: border-color .2s, box-shadow .2s; }
  .form-row input[type="text"]   { width: 230px; }
  .form-row input[type="number"] { width: 110px; }
  .form-row select { min-width: 200px; }
  .form-row input:focus, .form-row select:focus { border-color: #2563eb; box-shadow: 0 0 0 3px rgba(37,99,235,.15); background: #fff; }

  .reject-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
  .reject-row input { padding: 9px 14px; border: 1px solid #fca5a5; border-radius: 7px; font-size: .9rem; font-family: inherit; background: #fff; outline: none; width: 260px; transition: border-color .2s; }
  .reject-row input:focus { border-color: #dc2626; box-shadow: 0 0 0 3px rgba(220,38,38,.12); }

  .upload-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
  .upload-row input[type="file"] { font-size: .88rem; color: #374151; font-family: inherit; }
  .upload-note { font-size: .8rem; color: #6b7280; margin-top: 8px; }

  .btn { display: inline-flex; align-items: center; gap: 6px; padding: 9px 20px; border: none; border-radius: 7px; font-size: .9rem; font-weight: 600; cursor: pointer; font-family: inherit; transition: background .2s, transform .1s; }
  .btn:active { transform: scale(.97); }
  .btn-primary   { background: #2563eb; color: #fff; } .btn-primary:hover   { background: #1d4ed8; }
  .btn-success   { background: #16a34a; color: #fff; } .btn-success:hover   { background: #15803d; }
  .btn-warning   { background: #d97706; color: #fff; } .btn-warning:hover   { background: #b45309; }
  .btn-danger    { background: #dc2626; color: #fff; } .btn-danger:hover    { background: #b91c1c; }
  .btn-secondary { background: #e5e7eb; color: #374151; } .btn-secondary:hover { background: #d1d5db; }

  .badge { display: inline-block; padding: 3px 12px; border-radius: 20px; font-size: .78rem; font-weight: 700; }
  .badge-draft     { background: #f3f4f6; color: #6b7280; border: 1px solid #d1d5db; }
  .badge-submitted { background: #dbeafe; color: #1e40af; }
  .badge-approved  { background: #d1fae5; color: #065f46; }
  .badge-rejected  { background: #fee2e2; color: #991b1b; }
  .deal-consign { background: #ede9fe; color: #4c1d95; padding: 3px 10px; border-radius: 20px; font-size: .78rem; font-weight: 700; }
  .deal-direct  { background: #dbeafe; color: #1e40af; padding: 3px 10px; border-radius: 20px; font-size: .78rem; font-weight: 700; }
  .deal-free    { background: #d1fae5; color: #065f46; padding: 3px 10px; border-radius: 20px; font-size: .78rem; font-weight: 700; }

  .table-meta { font-size: .85rem; color: #6b7280; padding: 12px 24px 0; }
  table { width: 100%; border-collapse: collapse; }
  thead th { background: #f1f5f9; color: #374151; font-weight: 600; font-size: .875rem; padding: 12px 18px; text-align: right; border-bottom: 2px solid #e5e7eb; }
  tbody tr { border-bottom: 1px solid #f3f4f6; transition: background .15s; }
  tbody tr:hover { background: #f8faff; }
  tbody tr:last-child { border-bottom: none; }
  tbody td { padding: 12px 18px; font-size: .9rem; color: #374151; text-align: right; }

  .actions-bar { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; }
  .divider { width: 1px; height: 32px; background: #e5e7eb; }

  .empty-state { text-align: center; padding: 40px 20px; color: #9ca3af; }
  .empty-state .icon { font-size: 2.2rem; margin-bottom: 10px; }
  .empty-state p { font-size: .9rem; }

  .btn-open { display: inline-flex; align-items: center; gap: 5px; color: #2563eb; text-decoration: none; font-size: .85rem; font-weight: 500; padding: 4px 12px; border-radius: 6px; border: 1px solid #bfdbfe; background: #eff6ff; transition: background .2s; }
  .btn-open:hover { background: #dbeafe; }

  .info-note { background: #eff6ff; border: 1px solid #bfdbfe; border-radius: 8px; padding: 10px 16px; color: #1e40af; font-size: .85rem; margin-top: 12px; display: flex; gap: 8px; align-items: flex-start; }
</style>
</head>
<body>

<a class="back-link" href="../dashboard.php">→ العودة للرئيسية</a>

<?php if ($action === 'edit' && $delivery):
  [$status_ar, $status_cls] = odl_status_ar($delivery['status']);
  [$deal_ar_txt, $deal_cls] = deal_ar($delivery['deal_type']);
  $editable = in_array($delivery['status'], ['DRAFT','REJECTED'], true);
?>

<div class="page-header">
  <div>
    <h1>🚛 شحن للمنافذ — تعديل</h1>
    <div class="subtitle">مراجعة وإدارة أمر التسليم للمنفذ</div>
  </div>
  <?php if ($delivery['delivery_no']): ?>
    <div class="doc-badge"><?= h($delivery['delivery_no']) ?></div>
  <?php else: ?>
    <div class="doc-badge" style="opacity:.6;">لم يُولَّد رقم بعد</div>
  <?php endif; ?>
</div>

<div class="content">

  <div class="meta-bar">
    <div class="meta-item"><span class="meta-label">رقم المستند</span><span class="meta-value"><?= $delivery['delivery_no'] ? h($delivery['delivery_no']) : '—' ?></span></div>
    <div class="meta-item"><span class="meta-label">الموزع</span><span class="meta-value"><?= h($delivery['distributor_name']) ?></span></div>
    <div class="meta-item"><span class="meta-label">المنفذ</span><span class="meta-value"><?= h($delivery['outlet_name']) ?></span></div>
    <div class="meta-item"><span class="meta-label">نوع التعامل</span><span class="<?= $deal_cls ?>"><?= $deal_ar_txt ?></span></div>
    <div class="meta-item"><span class="meta-label">تاريخ التسليم</span><span class="meta-value"><?= h($delivery['delivery_at']) ?></span></div>
    <div class="meta-item"><span class="meta-label">أنشئ بواسطة</span><span class="meta-value"><?= h($delivery['created_by_name']) ?></span></div>
    <?php if ($delivery['manager_by_name']): ?>
    <div class="meta-item"><span class="meta-label">المدير / التوقيت</span><span class="meta-value"><?= h($delivery['manager_by_name']) ?> — <?= h($delivery['manager_at']) ?></span></div>
    <?php endif; ?>
    <div class="meta-item"><span class="meta-label">الحالة</span><span class="badge <?= $status_cls ?>"><?= $status_ar ?></span
></div>
  </div>

  <?php if ($delivery['manager_reason']): ?>
  <div class="alert-danger">
    <span>⚠️</span>
    <div><strong>سبب الرفض:</strong> <?= h($delivery['manager_reason']) ?></div>
  </div>
  <?php endif; ?>

  <!-- إضافة صنف -->
  <?php if ($editable): ?>
  <div class="card">
    <div class="card-header">➕ إضافة إصدار</div>
    <div class="card-body">
      <form method="post">
        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
        <input type="hidden" name="op" value="add_item">
        <input type="hidden" name="delivery_id" value="<?= (int)$delivery['id'] ?>">
        <div class="form-row">
          <label>
            الإصدار
            <select name="issue_id" required>
              <option value="">— اختر الإصدار —</option>
              <?php foreach ($issues as $iss): ?>
                <option value="<?= (int)$iss['id'] ?>"><?= h($iss['label']) ?></option>
              <?php endforeach; ?>
            </select>
          </label>
          <label>
            الكمية
            <input type="number" name="qty" min="1" step="1" placeholder="0" required>
          </label>
          <button type="submit" class="btn btn-primary">✔ إضافة</button>
        </div>
      </form>
      <?php if ($delivery['deal_type'] === 'DIRECT_SALE'): ?>
      <div class="info-note">
        ℹ️ نوع التعامل <strong>بيع مباشر</strong> — سيتم تسجيل سعر الوحدة تلقائياً من قواعد التسعير أو سعر الغلاف عند الإضافة.
      </div>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- جدول الأصناف -->
  <div class="card">
    <div class="card-header">📋 الأصناف</div>
    <div class="table-meta"><?= count($items) ?> صنف</div>
    <?php if (empty($items)): ?>
      <div class="empty-state">
        <div class="icon">🚛</div>
        <p>لم يُضَف أي إصدار بعد</p>
      </div>
    <?php else: ?>
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>الإصدار</th>
          <th>الكمية</th>
          <th>سعر الوحدة (ر.ع.)</th>
          <?php if ($editable): ?><th>حذف</th><?php endif; ?>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($items as $idx => $it): ?>
        <tr>
          <td><?= $idx + 1 ?></td>
          <td><strong><?= h($it['issue_label']) ?></strong></td>
          <td><?= number_format((int)$it['qty_delivered']) ?></td>
          <td>
            <?php if ($it['unit_price_applied'] !== null): ?>
              <?= number_format((float)$it['unit_price_applied'], 3) ?>
            <?php else: ?>
              <span style="color:#9ca3af;">—</span>
            <?php endif; ?>
          </td>
          <?php if ($editable): ?>
          <td>
            <form method="post" onsubmit="return confirm('هل تريد حذف هذا الصنف؟')">
              <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
              <input type="hidden" name="op" value="remove_item">
              <input type="hidden" name="delivery_id" value="<?= (int)$delivery['id'] ?>">
              <input type="hidden" name="item_id" value="<?= (int)$it['id'] ?>">
              <button type="submit" class="btn btn-danger" style="padding:5px 14px;font-size:.82rem;">🗑 حذف</button>
            </form>
          </td>
          <?php endif; ?>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>

  <!-- رفع POD -->
  <div class="card">
    <div class="card-header">📎 إيصال التسليم (POD)</div>
    <div class="card-body">
      <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
        <input type="hidden" name="op" value="upload_pod">
        <input type="hidden" name="delivery_id" value="<?= (int)$delivery['id'] ?>">
        <div class="upload-row">
          <input type="file" name="pod" accept=".jpg,.jpeg,.png,.pdf" required>
          <button type="submit" class="btn btn-secondary">📤 رفع الملف</button>
        </div>
        <div class="upload-note">ℹ️ إيصال التسليم يتضمن توقيع المستلم من المنفذ لتأكيد الاستلام.</div>
      </form>
      <?php if (!empty($delivery['pod_attachment_id'])): ?>
        <p style="margin-top:12px; color:#16a34a; font-weight:600;">✔ تم رفع إيصال التسليم</p>
      <?php endif; ?>
    </div>
  </div>

  <!-- الإجراءات -->
  <div class="card">
    <div class="card-header">⚙️ الإجراءات</div>
    <div class="card-body">
      <div class="actions-bar">

        <?php if ($editable): ?>
        <form method="post" onsubmit="return confirm('إرسال أمر التسليم للمراجعة؟')">
          <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
          <input type="hidden" name="op" value="submit">
          <input type="hidden" name="delivery_id" value="<?= (int)$delivery['id'] ?>">
          <button type="submit" class="btn btn-warning">📤 إرسال للمراجعة</button>
        </form>
        <?php endif; ?>

        <?php if ($me['role'] === 'ADMIN' && $delivery['status'] === 'SUBMITTED'): ?>
        <form method="post" onsubmit="return confirm('اعتماد أمر التسليم؟<?= $delivery["deal_type"]==="DIRECT_SALE" ? " (سيتم إنشاء فاتورة تلقائياً)" : "" ?>')">
          <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
          <input type="hidden" name="op" value="approve">
          <input type="hidden" name="delivery_id" value="<?= (int)$delivery['id'] ?>">
          <button type="submit" class="btn btn-success">
            ✔ اعتماد<?= $delivery['deal_type'] === 'DIRECT_SALE' ? ' (+ فاتورة)' : '' ?>
          </button>
        </form>

        <div class="divider"></div>

        <form method="post" class="reject-row">
          <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
          <input type="hidden" name="op" value="reject">
          <input type="hidden" name="delivery_id" value="<?= (int)$delivery['id'] ?>">
          <input type="text" name="reason" placeholder="سبب الرفض..." required>
          <button type="submit" class="btn btn-danger">✖ رفض</button>
        </form>
        <?php endif; ?>

        <?php if ($delivery['status'] === 'APPROVED'): ?>
          <span style="color:#16a34a; font-weight:600; display:flex; align-items:center; gap:6px;">
            ✔ تم اعتماد أمر التسليم بشكل نهائي
          </span>
        <?php endif; ?>

      </div>
    </div>
  </div>

</div><!-- /content edit -->

<?php else: /* ========== قائمة التسليمات ========== */ ?>

<div class="page-header">
  <div>
    <h1>🚛 شحن للمنافذ (ODL)</h1>
    <div class="subtitle">أوامر تسليم المجلات للمنافذ عبر الموزعين</div>
  </div>
  <div style="font-size:2rem; opacity:.2;">🚛</div>
</div>

<div class="content">

  <!-- إنشاء أمر جديد -->
  <div class="card">
    <div class="card-header">➕ إنشاء أمر تسليم جديد</div>
    <div class="card-body">
      <form method="post">
        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
        <input type="hidden" name="op" value="create">
        <div class="form-row">

          <?php if ($me['role'] !== 'DISTRIBUTOR'): ?>
          <label>
            الموزع
            <select name="distributor_id" required>
              <option value="">— اختر الموزع —</option>
              <?php foreach ($distributors as $dist): ?>
                <option value="<?= (int)$dist['id'] ?>"><?= h($dist['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </label>
          <?php else: ?>
          <input type="hidden" name="distributor_id" value="<?= (int)$me['distributor_id'] ?>">
          <?php endif; ?>

          <label>
            المنفذ
            <select name="outlet_id" required>
              <option value="">— اختر المنفذ —</option>
              <?php foreach ($outlets as $o): ?>
                <option value="<?= (int)$o['id'] ?>"><?= h($o['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </label>

          <label>
            نوع التعامل
            <select name="deal_type">
              <option value="CONSIGNMENT">أمانة</option>
              <option value="DIRECT_SALE">بيع مباشر</option>
              <option value="FREE">مجانية</option>
            </select>
          </label>

          <label>
            تاريخ التسليم
            <input type="text" name="delivery_at" value="<?= h(date('Y-m-d H:i:s')) ?>" placeholder="YYYY-MM-DD HH:MM:SS" required>
          </label>

          <button type="submit" class="btn btn-primary">➕ إنشاء</button>
        </div>
      </form>
    </div>
  </div>

  <!-- قائمة التسليمات -->
  <div class="card">
    <div class="card-header">📋 آخر 200 أمر تسليم</div>
    <div class="table-meta"><?= count($rows) ?> أمر</div>

    <?php if (empty($rows)): ?>
      <div class="empty-state">
        <div class="icon">🚛</div>
        <p>لا توجد أوامر تسليم مسجلة بعد</p>
      </div>
    <?php else: ?>
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>رقم الأمر</th>
          <th>التاريخ</th>
          <th>الموزع</th>
          <th>المنفذ</th>
          <th>نوع التعامل</th>
          <th>الحالة</th>
          <th>فتح</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $idx => $r):
          [$st_ar, $st_cls]  = odl_status_ar($r['status']);
          [$dl_ar, $dl_cls]  = deal_ar($r['deal_type']);
        ?>
        <tr>
          <td><?= $idx + 1 ?></td>
          <td>
            <?php if ($r['delivery_no']): ?>
              <strong><?= h($r['delivery_no']) ?></strong>
            <?php else: ?>
              <span style="color:#9ca3af; font-style:italic;">لم يُولَّد بعد</span>
            <?php endif; ?>
          </td>
          <td><?= h($r['delivery_at']) ?></td>
          <td><?= h($r['distributor_name']) ?></td>
          <td><?= h($r['outlet_name']) ?></td>
          <td><span class="<?= $dl_cls ?>"><?= $dl_ar ?></span></td>
          <td><span class="badge <?= $st_cls ?>"><?= $st_ar ?></span></td>
          <td>
            <a href="outlet_deliveries.php?action=edit&id=<?= (int)$r['id'] ?>" class="btn-open">
              📂 فتح
            </a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>

</div><!-- /content list -->

<?php endif; ?>

</body>
</html>
