<?php
session_save_path(__DIR__ . '/../tmp');
if (!is_dir(__DIR__ . '/../tmp')) mkdir(__DIR__ . '/../tmp', 0777, true);
session_start();

if (!isset($_SESSION['user_id'])) {
  header("Location: /wood-system/login.php");
  exit;
}

require __DIR__ . '/../includes/db.php';
require __DIR__ . '/../includes/header.php';

$cust_id = (int)($_GET['customer_id'] ?? 0);
$customers = $pdo->query("SELECT id,name FROM customers ORDER BY name")->fetchAll();
$movements = [];

if ($cust_id) {
  // 🔹 فواتير المبيعات
  $q1 = $pdo->prepare("
    SELECT si.date, 
           CONCAT('فاتورة مبيعات رقم ', si.id) AS descp, 
           si.total AS debit, 
           0 AS credit
    FROM sales_invoices si
    WHERE si.customer_id = ?
  ");
  $q1->execute([$cust_id]);
  foreach($q1 as $r){ $movements[] = $r; }

  // 🔹 قبض من العميل (دفعة كاش)
  $q2 = $pdo->prepare("
    SELECT date, CONCAT('قبض من العميل: ', COALESCE(note,'')) AS descp, 
           0 AS debit, amount AS credit
    FROM customer_money 
    WHERE customer_id=? AND type='in'
  ");
  $q2->execute([$cust_id]);
  foreach($q2 as $r){ $movements[] = $r; }

  // 🔹 صرف للعميل (مرتجعات / خصومات)
  $q3 = $pdo->prepare("
    SELECT date, CONCAT('دفع للعميل: ', COALESCE(note,'')) AS descp, 
           amount AS debit, 0 AS credit
    FROM customer_money 
    WHERE customer_id=? AND type='out'
  ");
  $q3->execute([$cust_id]);
  foreach($q3 as $r){ $movements[] = $r; }

  usort($movements, fn($a,$b)=>strcmp($a['date'],$b['date']));
}
?>
<h3 class="mb-3">📘 كشف حساب عميل</h3>
<form class="row g-3 mb-3">
  <div class="col-md-6">
    <label class="form-label">اختر العميل</label>
    <select name="customer_id" class="form-select" onchange="this.form.submit()">
      <option value="">— اختر —</option>
      <?php foreach($customers as $c): ?>
      <option value="<?= $c['id'] ?>" <?= $cust_id==$c['id']?'selected':'' ?>><?= htmlspecialchars($c['name']) ?></option>
      <?php endforeach; ?>
    </select>
  </div>
</form>

<?php if($cust_id): ?>
<div class="card shadow-sm"><div class="card-body p-0">
<div class="table-responsive">
<table class="table table-striped mb-0 text-center align-middle">
<thead class="table-dark">
<tr><th>التاريخ</th><th>البيان</th><th>مدين</th><th>دائن</th><th>الرصيد</th></tr>
</thead>
<tbody>
<?php $run=0; $d=0; $c=0;
foreach($movements as $m):
  $run += ($m['debit'] - $m['credit']);
  $d += $m['debit']; $c += $m['credit'];
?>
<tr>
  <td><?= htmlspecialchars($m['date']) ?></td>
  <td><?= htmlspecialchars($m['descp']) ?></td>
  <td><?= number_format($m['debit'],2) ?></td>
  <td><?= number_format($m['credit'],2) ?></td>
  <td><?= number_format($run,2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr class="table-light">
  <th colspan="2">الإجمالي</th>
  <th><?= number_format($d,2) ?></th>
  <th><?= number_format($c,2) ?></th>
  <th><?= number_format($d-$c,2) ?></th>
</tr>
</tfoot>
</table>
</div></div></div>
<?php endif; ?>

<?php require __DIR__ . '/../includes/footer.php'; ?>
