<?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/ledger.php';
require_once __DIR__ . '/../app/notify.php';
require_once __DIR__ . '/../app/audit.php';

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

function fetch_open_issues(PDO $pdo): array {
    return $pdo->query("SELECT i.id, p.name AS product_name, i.issue_month, i.issue_year, i.issue_number, i.title
                        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 issue_label(array $i): string {
    $no = $i['issue_number'] !== null ? $i['issue_number'] : '';
    return 'عدد '. $no .' - '.str_pad((string)$i['issue_month'],2,'0',STR_PAD_LEFT).'/'.$i['issue_year'].' — '.$i['product_name'];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $op = $_POST['op'] ?? '';

    if ($op === 'create') {
        if ($me['role'] !== 'DISTRIBUTOR') exit('Forbidden');
        $distributor_id = (int)($me['distributor_id'] ?? 0);
        if ($distributor_id <= 0) exit('Distributor not linked');

        $issue_id = (int)($_POST['issue_id'] ?? 0);
        $qty      = (int)($_POST['qty'] ?? 0);
        $note     = trim($_POST['note'] ?? '');

        if ($issue_id <= 0 || $qty <= 0) {
            flash('برجاء اختيار الإصدار وإدخال كمية صحيحة.','danger');
            redirect('distributor_orders.php');
        }

        $pdo->beginTransaction();
        try {
            $st = $pdo->prepare("INSERT INTO distributor_orders (distributor_id, status, note, created_by, created_at) VALUES (?,?,?,?,NOW())");
            $st->execute([$distributor_id, 'PENDING', $note !== '' ? $note : null, (int)$me['id']]);
            $order_id = (int)$pdo->lastInsertId();

            $pdo->prepare("INSERT INTO distributor_order_items (order_id, issue_id, qty_requested) VALUES (?,?,?)")
                ->execute([$order_id, $issue_id, $qty]);

            notify_role($pdo, 'ADMIN', 'طلب موزع جديد', 'يوجد طلب موزع بانتظار المراجعة', 'DIST_ORDER', $order_id, 'modules/distributor_orders.php');
            audit_log($pdo, (int)$me['id'], 'CREATE', 'distributor_orders', $order_id, ['issue_id'=>$issue_id,'qty'=>$qty]);

            $pdo->commit();
            flash('تم إرسال الطلب للمراجعة.','success');
        } catch (Throwable $e) {
            $pdo->rollBack();
            flash('حدث خطأ أثناء إنشاء الطلب.','danger');
        }
        redirect('distributor_orders.php');
    }

    if ($op === 'approve') {
        require_role(['ADMIN']);
        $order_id = (int)($_POST['order_id'] ?? 0);
        $o = $pdo->prepare("SELECT * FROM distributor_orders WHERE id=?");
        $o->execute([$order_id]);
        $order = $o->fetch();
        if (!$order) exit('Not found');
        if ($order['status'] !== 'PENDING') exit('Bad status');

        $pdo->prepare("UPDATE distributor_orders SET status='APPROVED', admin_reason=NULL, approved_by=?, approved_at=NOW() WHERE id=?")
            ->execute([(int)$me['id'], $order_id]);

        // notify distributor + warehouse
        $u = $pdo->prepare("SELECT id FROM users WHERE role='DISTRIBUTOR' AND distributor_id=? LIMIT 1");
        $u->execute([(int)$order['distributor_id']]);
        if ($uid = $u->fetchColumn()) {
            notify_user($pdo, (int)$uid, 'تمت الموافقة على الطلب', 'تمت الموافقة على طلبك، وسيتم تجهيز الصرف من المخزن.', 'DIST_ORDER', $order_id, 'modules/distributor_orders.php');
        }
        notify_role($pdo, 'WAREHOUSE', 'طلب موزع معتمد', 'يوجد طلب موزع معتمد بانتظار التنفيذ.', 'DIST_ORDER', $order_id, 'modules/distributor_orders.php');
        audit_log($pdo, (int)$me['id'], 'APPROVE', 'distributor_orders', $order_id, []);

        redirect('distributor_orders.php');
    }

    if ($op === 'reject') {
        require_role(['ADMIN']);
        $order_id = (int)($_POST['order_id'] ?? 0);
        $reason = trim($_POST['reason'] ?? '');
        if ($reason === '') exit('Reason required');
        $o = $pdo->prepare("SELECT * FROM distributor_orders WHERE id=?");
        $o->execute([$order_id]);
        $order = $o->fetch();
        if (!$order) exit('Not found');
        if ($order['status'] !== 'PENDING') exit('Bad status');

        $pdo->prepare("UPDATE distributor_orders SET status='REJECTED', admin_reason=?, approved_by=?, approved_at=NOW() WHERE id=?")
            ->execute([$reason, (int)$me['id'], $order_id]);

        $u = $pdo->prepare("SELECT id FROM users WHERE role='DISTRIBUTOR' AND distributor_id=? LIMIT 1");
        $u->execute([(int)$order['distributor_id']]);
        if ($uid = $u->fetchColumn()) {
            notify_user($pdo, (int)$uid, 'تم رفض الطلب', 'تم رفض طلبك: '.$reason, 'DIST_ORDER', $order_id, 'modules/distributor_orders.php');
        }
        audit_log($pdo, (int)$me['id'], 'REJECT', 'distributor_orders', $order_id, ['reason'=>$reason]);
        redirect('distributor_orders.php');
    }

    if ($op === 'fulfill') {
        require_role(['WAREHOUSE']);
        $order_id = (int)($_POST['order_id'] ?? 0);
        $pdo->beginTransaction();
        try {
            $o = $pdo->prepare("SELECT * FROM distributor_orders WHERE id=? FOR UPDATE");
            $o->execute([$order_id]);
            $order = $o->fetch();
            if (!$order) throw new Exception('Not found');
            if ($order['status'] !== 'APPROVED') throw new Exception('Bad status');

            $it = $pdo->prepare("SELECT * FROM distributor_order_items WHERE order_id=?");
            $it->execute([$order_id]);
            $items = $it->fetchAll();
            if (!$items) throw new Exception('No items');

            // stock check
            foreach ($items as $row) {
                $need = (int)$row['qty_requested'];
                $bal = ledger_balance($pdo, 'WAREHOUSE', null, (int)$row['issue_id']);
                if ($bal < $need) throw new Exception('رصيد المخزن غير كافي لتنفيذ الطلب.');
            }

            foreach ($items as $row) {
                $issueId = (int)$row['issue_id'];
                $qty = (int)$row['qty_requested'];
                ledger_post($pdo, 'WAREHOUSE', null, $issueId, 0, $qty, 'DIST_ORDER', $order_id, (int)$me['id']);
                ledger_post($pdo, 'DISTRIBUTOR', (int)$order['distributor_id'], $issueId, $qty, 0, 'DIST_ORDER', $order_id, (int)$me['id']);
                $pdo->prepare("UPDATE distributor_order_items SET qty_fulfilled=? WHERE id=?")
                    ->execute([$qty, (int)$row['id']]);
            }

            $pdo->prepare("UPDATE distributor_orders SET status='FULFILLED', fulfilled_by=?, fulfilled_at=NOW() WHERE id=?")
                ->execute([(int)$me['id'], $order_id]);

            $u = $pdo->prepare("SELECT id FROM users WHERE role='DISTRIBUTOR' AND distributor_id=? LIMIT 1");
            $u->execute([(int)$order['distributor_id']]);
            if ($uid = $u->fetchColumn()) {
                notify_user($pdo, (int)$uid, 'تم تنفيذ الطلب', 'تم تنفيذ الطلب وصرف الكمية. يمكنك التوجه للمخزن للاستلام.', 'DIST_ORDER', $order_id, 'modules/distributor_orders.php');
            }
            audit_log($pdo, (int)$me['id'], 'UPDATE', 'distributor_orders', $order_id, ['status'=>'FULFILLED']);

            $pdo->commit();
            flash('تم تنفيذ الصرف بنجاح.','success');
        } catch (Throwable $e) {
            $pdo->rollBack();
            flash($e->getMessage(),'danger');
        }
        redirect('distributor_orders.php');
    }
}

// Data for page
$issues = fetch_open_issues($pdo);

$where = "";
$params = [];
if ($me['role'] === 'DISTRIBUTOR') {
    $where = "WHERE o.distributor_id=?";
    $params[] = (int)$me['distributor_id'];
} elseif ($me['role'] === 'WAREHOUSE') {
    $where = "WHERE o.status IN ('APPROVED','FULFILLED')";
} else {
    $where = "";
}

$st = $pdo->prepare("SELECT o.*, d.name AS distributor_name, u.name AS created_by_name
                     FROM distributor_orders o
                     JOIN distributors d ON d.id=o.distributor_id
                     JOIN users u ON u.id=o.created_by
                     $where
                     ORDER BY o.id DESC
                     LIMIT 200");
$st->execute($params);
$orders = $st->fetchAll();

function order_items(PDO $pdo, int $orderId): array {
    $st = $pdo->prepare("SELECT oi.*, p.name AS product_name, i.issue_month, i.issue_year, i.issue_number
                         FROM distributor_order_items oi
                         JOIN issues i ON i.id=oi.issue_id
                         JOIN products p ON p.id=i.product_id
                         WHERE oi.order_id=?");
    $st->execute([$orderId]);
    return $st->fetchAll();
}

?><!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>طلبات الموزعين — MGZ</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body{font-family:Segoe UI,Tahoma,Arial,sans-serif;background:#f3f4f6;margin:0;color:#111827;direction:rtl}
.header{background:linear-gradient(135deg,#1e3a5f,#2563eb);color:#fff;padding:18px 22px;margin:20px;border-radius:12px;display:flex;justify-content:space-between;align-items:center}
.header a{color:#fff;text-decoration:none;opacity:.9}
.container{max-width:1100px;margin:0 auto;padding:0 20px 40px}
.card{background:#fff;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.08);margin-bottom:18px;overflow:hidden}
.card .hd{padding:14px 18px;border-bottom:1px solid #e5e7eb;font-weight:700}
.card .bd{padding:18px}
.table{width:100%;border-collapse:collapse}
.table th,.table td{padding:10px 12px;border-bottom:1px solid #eef2f7;text-align:right;font-size:.92rem}
.table th{background:#f8fafc;font-weight:700}
.btn{border:0;border-radius:8px;padding:8px 14px;cursor:pointer;font-weight:700}
.btn-primary{background:#2563eb;color:#fff}
.btn-success{background:#16a34a;color:#fff}
.btn-danger{background:#dc2626;color:#fff}
input,select,textarea{padding:9px 10px;border:1px solid #d1d5db;border-radius:8px;width:100%;font-family:inherit}
.row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.badge{display:inline-block;padding:3px 10px;border-radius:999px;font-size:.78rem;font-weight:800}
.b-pending{background:#fef3c7;color:#92400e}
.b-approved{background:#dbeafe;color:#1e40af}
.b-rejected{background:#fee2e2;color:#991b1b}
.b-fulfilled{background:#d1fae5;color:#065f46}
</style>
</head>
<body>
<div class="header">
  <div><strong>طلبات الموزعين</strong> <span style="opacity:.85">(Workflow: موزع → إدارة → مخزن)</span></div>
  <div><a href="../dashboard.php">⬅ رجوع للوحة التحكم</a></div>
</div>
<div class="container">
  <?php show_flash(); ?>

  <?php if ($me['role']==='DISTRIBUTOR'): ?>
  <div class="card">
    <div class="hd">➕ إنشاء طلب جديد</div>
    <div class="bd">
      <form method="post">
        <input type="hidden" name="csrf" value="<?=h($csrf)?>">
        <input type="hidden" name="op" value="create">
        <div class="row">
          <div>
            <label>الإصدار</label>
            <select name="issue_id" required>
              <option value="">— اختر —</option>
              <?php foreach($issues as $i): ?>
                <option value="<?= (int)$i['id'] ?>"><?= h(issue_label($i)) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label>الكمية المطلوبة</label>
            <input type="number" name="qty" min="1" required>
          </div>
        </div>
        <div style="margin-top:12px">
          <label>ملاحظة (اختياري)</label>
          <textarea name="note" rows="2"></textarea>
        </div>
        <div style="margin-top:12px">
          <button class="btn btn-primary" type="submit">إرسال للمراجعة</button>
        </div>
      </form>
    </div>
  </div>
  <?php endif; ?>

  <div class="card">
    <div class="hd">📋 الطلبات</div>
    <div class="bd" style="padding:0">
      <table class="table">
        <thead>
          <tr>
            <th>#</th>
            <th>الموزع</th>
            <th>الحالة</th>
            <th>محتوى الطلب</th>
            <th>تاريخ الإنشاء</th>
            <th>إجراءات</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach($orders as $o): $items = order_items($pdo,(int)$o['id']); ?>
          <tr>
            <td><?= (int)$o['id'] ?></td>
            <td><?= h($o['distributor_name']) ?></td>
            <td>
              <?php
                $cls = match($o['status']){
                  'PENDING'=>'b-pending',
                  'APPROVED'=>'b-approved',
                  'REJECTED'=>'b-rejected',
                  'FULFILLED'=>'b-fulfilled',
                  default=>'b-pending'
                };
              ?>
              <span class="badge <?= $cls ?>"><?= h($o['status']) ?></span>
            </td>
            <td>
              <?php foreach($items as $it): ?>
                <div><?= h('عدد '.($it['issue_number']??'').' '.str_pad((string)$it['issue_month'],2,'0',STR_PAD_LEFT).'/'.$it['issue_year'].' — '.$it['product_name']) ?> (<?= (int)$it['qty_requested'] ?>)</div>
              <?php endforeach; ?>
              <?php if (!empty($o['note'])): ?><div style="color:#6b7280;font-size:.85rem">📝 <?= h($o['note']) ?></div><?php endif; ?>
              <?php if (!empty($o['admin_reason'])): ?><div style="color:#b91c1c;font-size:.85rem">⚠ <?= h($o['admin_reason']) ?></div><?php endif; ?>
            </td>
            <td><?= h($o['created_at']) ?></td>
            <td>
              <?php if ($me['role']==='ADMIN' && $o['status']==='PENDING'): ?>
                <form method="post" style="display:inline-block" onsubmit="return confirm('اعتماد الطلب؟');">
                  <input type="hidden" name="csrf" value="<?=h($csrf)?>">
                  <input type="hidden" name="op" value="approve">
                  <input type="hidden" name="order_id" value="<?= (int)$o['id'] ?>">
                  <button class="btn btn-success" type="submit">اعتماد</button>
                </form>
                <form method="post" style="display:inline-block">
                  <input type="hidden" name="csrf" value="<?=h($csrf)?>">
                  <input type="hidden" name="op" value="reject">
                  <input type="hidden" name="order_id" value="<?= (int)$o['id'] ?>">
                  <input type="text" name="reason" placeholder="سبب الرفض" required style="width:160px;display:inline-block">
                  <button class="btn btn-danger" type="submit">رفض</button>
                </form>
              <?php elseif ($me['role']==='WAREHOUSE' && $o['status']==='APPROVED'): ?>
                <form method="post" onsubmit="return confirm('تنفيذ الصرف؟ سيتم خصم الكمية من المخزن وإضافتها للموزع.');">
                  <input type="hidden" name="csrf" value="<?=h($csrf)?>">
                  <input type="hidden" name="op" value="fulfill">
                  <input type="hidden" name="order_id" value="<?= (int)$o['id'] ?>">
                  <button class="btn btn-success" type="submit">تنفيذ الصرف</button>
                </form>
              <?php else: ?>—<?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if (empty($orders)): ?>
          <tr><td colspan="6" style="text-align:center;color:#6b7280;padding:18px">لا توجد بيانات</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
</body>
</html>
