<?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';

$me = require_role(['ADMIN','DISTRIBUTOR']);
$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 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_settlement(PDO $pdo, int $id): ?array {
  $st = $pdo->prepare("
    SELECT os.*,
           u1.name AS created_by_name,
           u2.name AS manager_by_name,
           dist.name AS distributor_name,
           o.name AS outlet_name
    FROM outlet_settlements os
    JOIN users u1 ON u1.id=os.created_by
    LEFT JOIN users u2 ON u2.id=os.manager_by
    JOIN distributors dist ON dist.id=os.distributor_id
    JOIN outlets o ON o.id=os.outlet_id
    WHERE os.id=?
  ");
  $st->execute([$id]);
  $r = $st->fetch();
  return $r ?: null;
}
function fetch_settlement_lines(PDO $pdo, int $settlementId): array {
  $st = $pdo->prepare("
    SELECT osl.*, CONCAT(p.name,' - ',LPAD(i.issue_month,2,'0'),'/',i.issue_year) AS issue_label
    FROM outlet_settlement_lines osl
    JOIN issues i ON i.id=osl.issue_id
    JOIN products p ON p.id=i.product_id
    WHERE osl.settlement_id=?
    ORDER BY issue_label
  ");
  $st->execute([$settlementId]);
  return $st->fetchAll();
}
function resolve_unit_price(PDO $pdo, int $outletId, int $issueId, string $settlementAt): 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, $settlementAt, $settlementAt]);
  $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 distributor_commission(PDO $pdo, int $distributorId, float $grossAmount): float {
  $st = $pdo->prepare("SELECT commission_type, commission_value FROM distributors WHERE id=?");
  $st->execute([$distributorId]);
  $d = $st->fetch();
  if (!$d) return 0.0;
  if ($d['commission_type'] === 'PERCENT') return round($grossAmount * max(0.0, (float)$d['commission_value']) / 100.0, 3);
  if ($d['commission_type'] === 'FIXED')   return round(max(0.0, (float)$d['commission_value']), 3);
  return 0.0;
}

$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);
    $settlement_at  = trim($_POST['settlement_at']    ?? '');
    if ($forcedDistributorId !== null) $distributor_id = $forcedDistributorId;
    if ($distributor_id<=0 || $outlet_id<=0 || $settlement_at==='') exit("Bad data");
    $st = $pdo->prepare("INSERT INTO outlet_settlements (settlement_no, distributor_id, outlet_id, settlement_at, created_by, status) VALUES (NULL, ?, ?, ?, ?, 'DRAFT')");
    $st->execute([$distributor_id, $outlet_id, $settlement_at, (int)$me['id']]);
    redirect("settlements.php?action=edit&id=".(int)$pdo->lastInsertId());
  }

  if ($op === 'add_line') {
    $settlement_id = (int)($_POST['settlement_id'] ?? 0);
    $issue_id      = (int)($_POST['issue_id']      ?? 0);
    $qty_sold      = (int)($_POST['qty_sold']       ?? 0);
    $qty_returned  = (int)($_POST['qty_returned']   ?? 0);
    $qty_damaged   = (int)($_POST['qty_damaged']    ?? 0);
    if ($settlement_id<=0 || $issue_id<=0) exit("Bad data");
    if ($qty_sold<0 || $qty_returned<0 || $qty_damaged<0) exit("Quantities must be >=0");
    $s = fetch_settlement($pdo, $settlement_id);
    if (!$s) exit("Settlement not found");
    if ($me['role'] === 'DISTRIBUTOR' && (int)$s['distributor_id'] !== (int)$me['distributor_id']) exit("Forbidden");
    if (!in_array($s['status'], ['DRAFT','REJECTED'], true)) exit("Cannot edit in this status");
    $unit  = resolve_unit_price($pdo, (int)$s['outlet_id'], $issue_id, $s['settlement_at']);
    $gross = round($qty_sold * $unit, 3);
    $comm  = distributor_commission($pdo, (int)$s['distributor_id'], $gross);
    $net   = round(max(0.0, $gross - $comm), 3);
    $pdo->prepare("
      INSERT INTO outlet_settlement_lines
        (settlement_id, issue_id, qty_sold, qty_returned, qty_damaged, unit_price_applied, gross_amount, distributor_commission, net_due)
      VALUES (?,?,?,?,?,?,?,?,?)
      ON DUPLICATE KEY UPDATE
        qty_sold=VALUES(qty_sold), qty_returned=VALUES(qty_returned), qty_damaged=VALUES(qty_damaged),
        unit_price_applied=VALUES(unit_price_applied), gross_amount=VALUES(gross_amount),
        distributor_commission=VALUES(distributor_commission), net_due=VALUES(net_due)
    ")->execute([$settlement_id, $issue_id, $qty_sold, $qty_returned, $qty_damaged, $unit, $gross, $comm, $net]);
    redirect("settlements.php?action=edit&id=".$settlement_id);
  }

  if ($op === 'delete_line') {
    $settlement_id = (int)($_POST['settlement_id'] ?? 0);
    $line_id       = (int)($_POST['line_id']       ?? 0);
    $s = fetch_settlement($pdo, $settlement_id);
    if (!$s) exit("Settlement not found");
    if ($me['role'] === 'DISTRIBUTOR' && (int)$s['distributor_id'] !== (int)$me['distributor_id']) exit("Forbidden");
    if (!in_array($s['status'], ['DRAFT','REJECTED'], true)) exit("Cannot edit in this status");
    $pdo->prepare("DELETE FROM outlet_settlement_lines WHERE id=? AND settlement_id=?")->execute([$line_id, $settlement_id]);
    redirect("settlements.php?action=edit&id=".$settlement_id);
  }

  if ($op === 'submit') {
    $settlement_id = (int)($_POST['settlement_id'] ?? 0);
    $s = fetch_settlement($pdo, $settlement_id);
    if (!$s) exit("Settlement not found");
    if ($me['role'] === 'DISTRIBUTOR' && (int)$s['distributor_id'] !== (int)$me['distributor_id']) exit("Forbidden");
    if (!in_array($s['status'], ['DRAFT','REJECTED'], true)) exit("Bad status");
    $cnt = $pdo->prepare("SELECT COUNT(*) c FROM outlet_settlement_lines WHERE settlement_id=?");
    $cnt->execute([$settlement_id]);
    if ((int)$cnt->fetch()['c'] <= 0) exit("Add lines first");
    if (empty($s['settlement_no'])) {
      $no = next_doc_no('OST', new DateTimeImmutable($s['settlement_at']));
      $pdo->prepare("UPDATE outlet_settlements SET settlement_no=? WHERE id=?")->execute([$no, $settlement_id]);
    }
    $pdo->prepare("UPDATE outlet_settlements SET status='SUBMITTED' WHERE id=?")->execute([$settlement_id]);
    redirect("settlements.php?action=edit&id=".$settlement_id);
  }

  if ($op === 'approve') {
    require_role(['ADMIN']);
    $settlement_id = (int)($_POST['settlement_id'] ?? 0);
    $s = fetch_settlement($pdo, $settlement_id);
    if (!$s) exit("Settlement not found");
    if ($s['status'] !== 'SUBMITTED') exit("Only SUBMITTED can be approved");
    $pdo->beginTransaction();
    try {
      $pdo->prepare("UPDATE outlet_settlements SET status='APPROVED', manager_by=?, manager_at=NOW(), manager_reason=NULL WHERE id=?")->execute([(int)$me['id'], $settlement_id]);
      $invNo = next_doc_no('INV', new DateTimeImmutable($s['settlement_at']));
      $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 (?, ?, ?, 'CONSIGNMENT_SETTLEMENT', ?, ?, 'ISSUED', 'OMR', 0, 0, 0, ?)")->execute([$invNo, (int)$s['outlet_id'], (int)$s['distributor_id'], $settlement_id, $s['settlement_at'], (int)$me['id']]);
      $invoiceId = (int)$pdo->lastInsertId();
      $linesQ = $pdo->prepare("SELECT issue_id, qty_sold, unit_price_applied FROM outlet_settlement_lines WHERE settlement_id=?");
      $linesQ->execute([$settlement_id]);
      $total = 0.0;
      foreach ($linesQ->fetchAll() as $r) {
        $qty = (int)$r['qty_sold']; $unit = (float)$r['unit_price_applied']; $lineTotal = round($qty * $unit, 3); $total += $lineTotal;
        $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([$invoiceId, (int)$r['issue_id'], $qty, $unit, $lineTotal]);
      }
      $total = round($total, 3);
      $pdo->prepare("UPDATE invoices SET total_amount=?, balance_due=? WHERE id=?")->execute([$total, $total, $invoiceId]);
      $pdo->commit();
      redirect("invoices.php?action=view&id=".$invoiceId);
    } catch (Throwable $e) { $pdo->rollBack(); throw $e; }
  }

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

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

$csrf = csrf_token();

function ost_status_ar(string $s): array {
  return match($s) {
    'DRAFT'     => ['مسودة',  'badge-draft'],
    'SUBMITTED' => ['مرسلة',  'badge-submitted'],
    'APPROVED'  => ['معتمدة', 'badge-approved'],
    'REJECTED'  => ['مرفوضة','badge-rejected'],
    default     => [$s,        'badge-draft'],
  };
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>تسويات الأمانة (OST) — 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; }
  .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; }

  .summary-grid { display: grid; grid-template-columns: repeat(3,1fr); gap: 16px; margin-bottom: 24px; }
  .summary-card { background: #fff; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,.07); padding: 20px; text-align: center; }
  .summary-card .s-label { font-size: .8rem; color: #6b7280; margin-bottom: 8px; }
  .summary-card .s-value { font-size: 1.5rem; font-weight: 700; }
  .s-blue  { color: #2563eb; }
  .s-red   { color: #dc2626; }
  .s-green { color: #16a34a; }

  .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; }

  .line-form-grid { display: grid; grid-template-columns: 2fr repeat(3, 110px); gap: 12px; align-items: flex-end; }
  .line-form-grid label { display: flex; flex-direction: column; gap: 5px; font-size: .82rem; color: #374151; font-weight: 500; }
  .line-form-grid input, .line-form-grid select { padding: 9px 14px; border: 1px solid #d1d5db; border-radius: 7px; font-size: .92rem; font-family: inherit; background: #f9fafb; color: #1f2937; outline: none; width: 100%; transition: border-color .2s, box-shadow .2s; }
  .line-form-grid input:focus, .line-form-grid select:focus { border-color: #2563eb; box-shadow: 0 0 0 3px rgba(37,99,235,.15); background: #fff; }

  .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 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); }

  .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; }

  .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: .82rem; padding: 11px 14px; 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: 11px 14px; font-size: .88rem; color: #374151; text-align: right; }
  tfoot td { padding: 11px 14px; font-size: .88rem; font-weight: 700; color: #1e3a5f; text-align: right; background: #f8faff; border-top: 2px solid #e5e7eb; }

  .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; }
  .num-green { color: #16a34a; font-weight: 700; }
  .num-blue  { color: #2563eb; font-weight: 700; }
  .num-red   { color: #dc2626; font-weight: 700; }
</style>
</head>
<body>

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

<?php if ($action === 'edit' && $settlement):
  [$status_ar, $status_cls] = ost_status_ar($settlement['status']);
  $editable    = in_array($settlement['status'], ['DRAFT','REJECTED'], true);
  $total_gross = array_sum(array_column($lines, 'gross_amount'));
  $total_comm  = array_sum(array_column($lines, 'distributor_commission'));
  $total_net   = array_sum(array_column($lines, 'net_due'));
?>

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

<div class="content">

  <!-- Meta Bar -->
  <div class="meta-bar">
    <div class="meta-item"><span class="meta-label">رقم المستند</span><span class="meta-value"><?= $settlement['settlement_no'] ? h($settlement['settlement_no']) : '—' ?></span></div>
    <div class="meta-item"><span class="meta-label">الموزع</span><span class="meta-value"><?= h($settlement['distributor_name']) ?></span></div>
    <div class="meta-item"><span class="meta-label">المنفذ</span><span class="meta-value"><?= h($settlement['outlet_name']) ?></span></div>
    <div class="meta-item"><span class="meta-label">تاريخ التسوية</span><span class="meta-value"><?= h($settlement['settlement_at']) ?></span></div>
    <div class="meta-item"><span class="meta-label">أنشئ بواسطة</span><span class="meta-value"><?= h($settlement['created_by_name']) ?></span>
    </div>
    <?php if ($settlement['manager_by_name']): ?>
    <div class="meta-item">
      <span class="meta-label">المدير / التوقيت</span>
      <span class="meta-value"><?= h($settlement['manager_by_name']) ?> — <?= h($settlement['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 ($settlement['manager_reason']): ?>
  <div class="alert-danger">
    <span>⚠️</span>
    <div><strong>سبب الرفض:</strong> <?= h($settlement['manager_reason']) ?></div>
  </div>
  <?php endif; ?>

  <?php if (!empty($lines)): ?>
  <div class="summary-grid">
    <div class="summary-card">
      <div class="s-label">إجمالي المبيعات</div>
      <div class="s-value s-blue"><?= number_format($total_gross,3) ?> <small style="font-size:.75rem;font-weight:400;">ر.ع.</small></div>
    </div>
    <div class="summary-card">
      <div class="s-label">عمولة الموزع</div>
      <div class="s-value s-red"><?= number_format($total_comm,3) ?> <small style="font-size:.75rem;font-weight:400;">ر.ع.</small></div>
    </div>
    <div class="summary-card">
      <div class="s-label">صافي المستحق</div>
      <div class="s-value s-green"><?= number_format($total_net,3) ?> <small style="font-size:.75rem;font-weight:400;">ر.ع.</small></div>
    </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_line">
        <input type="hidden" name="settlement_id" value="<?= (int)$settlement['id'] ?>">
        <div class="line-form-grid">
          <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_sold" min="0" step="1" placeholder="0" required></label>
          <label>مرتجع<input type="number" name="qty_returned" min="0" step="1" placeholder="0" required></label>
          <label>تالف<input type="number" name="qty_damaged" min="0" step="1" placeholder="0" required></label>
        </div>
        <div style="margin-top:14px;">
          <button type="submit" class="btn btn-primary">💾 حفظ السطر</button>
        </div>
      </form>
      <div class="info-note">ℹ️ الكميات التالفة تُحتسب على الشركة. الصافي = (مباع × سعر الوحدة) − عمولة الموزع.</div>
    </div>
  </div>
  <?php endif; ?>

  <div class="card">
    <div class="card-header">📊 سطور التسوية</div>
    <div class="table-meta"><?= count($lines) ?> سطر</div>
    <?php if (empty($lines)): ?>
      <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><th>الصافي</th>
          <?php if ($editable): ?><th>حذف</th><?php endif; ?>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($lines as $idx => $ln): ?>
        <tr>
          <td><?= $idx+1 ?></td>
          <td><strong><?= h($ln['issue_label']) ?></strong></td>
          <td class="num-green"><?= number_format((int)$ln['qty_sold']) ?></td>
          <td><?= number_format((int)$ln['qty_returned']) ?></td>
          <td class="num-red"><?= number_format((int)$ln['qty_damaged']) ?></td>
          <td><?= number_format((float)$ln['unit_price_applied'],3) ?></td>
          <td class="num-blue"><?= number_format((float)$ln['gross_amount'],3) ?></td>
          <td class="num-red"><?= number_format((float)$ln['distributor_commission'],3) ?></td>
          <td class="num-green"><?= number_format((float)$ln['net_due'],3) ?></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="delete_line">
              <input type="hidden" name="settlement_id" value="<?= (int)$settlement['id'] ?>">
              <input type="hidden" name="line_id" value="<?= (int)$ln['id'] ?>">
              <button type="submit" class="btn btn-danger" style="padding:5px 14px;font-size:.82rem;">🗑 حذف</button>
            </form>
          </td>
          <?php endif; ?>
        </tr>
        <?php endforeach; ?>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="6">الإجمالي</td>
          <td class="num-blue"><?= number_format($total_gross,3) ?></td>
          <td class="num-red"><?= number_format($total_comm,3) ?></td>
          <td class="num-green"><?= number_format($total_net,3) ?></td>
          <?php if ($editable): ?><td></td><?php endif; ?>
        </tr>
      </tfoot>
    </table>
    <?php endif; ?>
  </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="settlement_id" value="<?= (int)$settlement['id'] ?>">
          <button type="submit" class="btn btn-warning">📤 إرسال للمراجعة</button>
        </form>
        <?php endif; ?>

        <?php if ($me['role']==='ADMIN' && $settlement['status']==='SUBMITTED'): ?>
        <form method="post" onsubmit="return confirm('اعتماد التسوية وإنشاء الفاتورة؟')">
          <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
          <input type="hidden" name="op" value="approve">
          <input type="hidden" name="settlement_id" value="<?= (int)$settlement['id'] ?>">
          <button type="submit" class="btn btn-success">✔ اعتماد (+ فاتورة)</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="settlement_id" value="<?= (int)$settlement['id'] ?>">
          <input type="text" name="reason" placeholder="سبب الرفض..." required>
          <button type="submit" class="btn btn-danger">✖ رفض</button>
        </form>
        <?php endif; ?>

        <?php if ($settlement['status']==='APPROVED'): ?>
          <span style="color:#16a34a;font-weight:600;display:flex;align-items:center;gap:6px;">
            ✔ تمت الموافقة على التسوية وتم إنشاء الفاتورة
          </span>
        <?php endif; ?>

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

</div>

<?php else: ?>

<div class="page-header">
  <div>
    <h1>📋 تسويات الأمانة (OST)</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>تاريخ التسوية
            <input type="text" name="settlement_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] = ost_status_ar($r['status']);
        ?>
        <tr>
          <td><?= $idx+1 ?></td>
          <td><?= $r['settlement_no'] ? '<strong>'.h($r['settlement_no']).'</strong>' : '<span style="color:#9ca3af;font-style:italic;">لم يُولَّد بعد</span>' ?></td>
          <td><?= h($r['settlement_at']) ?></td>
          <td><?= h($r['distributor_name']) ?></td>
          <td><?= h($r['outlet_name']) ?></td>
          <td><span class="badge <?= $st_cls ?>"><?= $st_ar ?></span></td>
          <td><?= h($r['created_by_name']) ?></td>
          <td><a href="settlements.php?action=edit&id=<?= (int)$r['id'] ?>" class="btn-open">📂 فتح</a></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>

</div>

<?php endif; ?>

</body>
</html>
