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

error_reporting(E_ALL);
ini_set('display_errors', 1);

// ------------------- معالجة الإضافة / السحب اليدوي -------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_transaction'])) {
    $cashbox_id = intval($_POST['cashbox_id']);
    $type = $_POST['type'];
    $amount = floatval($_POST['amount']);
    $note = trim($_POST['note']);

    if ($amount > 0) {
        // تحديث الرصيد حسب نوع العملية
        if ($type === 'add') {
            $pdo->prepare("UPDATE cashbox SET balance = balance + ? WHERE id=?")->execute([$amount, $cashbox_id]);
        } elseif ($type === 'withdraw') {
            $pdo->prepare("UPDATE cashbox SET balance = balance - ? WHERE id=?")->execute([$amount, $cashbox_id]);
        }

        // إدخال السجل في جدول cashbox_log كمصدر manual
        $stmt = $pdo->prepare("INSERT INTO cashbox_log (cashbox_id, type, amount, note, source) VALUES (?, ?, ?, ?, 'manual')");
        $stmt->execute([$cashbox_id, $type, $amount, $note]);
    }

    header("Location: cashbox.php");
    exit;
}

// ------------------- تعديل عملية -------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_transaction'])) {
    $id = intval($_POST['id']);
    $amount = floatval($_POST['amount']);
    $note = trim($_POST['note']);

    $pdo->prepare("UPDATE cashbox_log SET amount=?, note=? WHERE id=?")->execute([$amount, $note, $id]);
    header("Location: cashbox.php");
    exit;
}

// ------------------- حذف عملية -------------------
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $stmt = $pdo->prepare("SELECT * FROM cashbox_log WHERE id=?");
    $stmt->execute([$id]);
    $log = $stmt->fetch();

    if ($log) {
        // 🚫 منع حذف عمليات المدفوعات أو النظام
        if ($log['source'] !== 'manual') {
            echo "<script>alert('❌ لا يمكن حذف عمليات مرتبطة بالمدفوعات أو النظام.');window.location='cashbox.php';</script>";
            exit;
        }

        // ✅ فقط العمليات اليدوية يمكن حذفها وتعديل الرصيد بناءً على نوعها
        if ($log['type'] === 'add') {
            $pdo->prepare("UPDATE cashbox SET balance = balance - ? WHERE id=?")->execute([$log['amount'], $log['cashbox_id']]);
        } else {
            $pdo->prepare("UPDATE cashbox SET balance = balance + ? WHERE id=?")->execute([$log['amount'], $log['cashbox_id']]);
        }

        $pdo->prepare("DELETE FROM cashbox_log WHERE id=?")->execute([$id]);
    }

    header("Location: cashbox.php");
    exit;
}

// ------------------- جلب الصناديق -------------------
$cashboxes = $pdo->query("SELECT * FROM cashbox ORDER BY id ASC")->fetchAll();

// ------------------- جلب السجل -------------------
$logs = $pdo->query("SELECT l.*, c.name AS cashbox_name 
                     FROM cashbox_log l 
                     JOIN cashbox c ON c.id = l.cashbox_id 
                     ORDER BY l.id DESC")->fetchAll();
?>

<h3 class="mb-4 text-center text-primary">💼 إدارة الصناديق</h3>

<div class="row g-3 mb-4">
  <?php foreach ($cashboxes as $c): ?>
  <div class="col-md-3">
    <div class="card shadow-sm text-center">
      <div class="card-body">
        <h5 class="text-dark"><?= htmlspecialchars($c['name']) ?></h5>
        <h4 class="text-success"><?= number_format($c['balance'], 2) ?> ₺</h4>

        <form method="post" class="mt-2">
          <input type="hidden" name="cashbox_id" value="<?= $c['id'] ?>">
          <select name="type" class="form-select mb-2" required>
            <option value="add">إيداع</option>
            <option value="withdraw">سحب</option>
          </select>
          <input type="number" step="0.01" name="amount" placeholder="المبلغ" required class="form-control mb-2">
          <input type="text" name="note" placeholder="ملاحظة" class="form-control mb-2">
          <button name="add_transaction" class="btn btn-primary w-100 btn-sm">تنفيذ</button>
        </form>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<h4 class="text-secondary mb-3">📜 سجل الحركات</h4>

<div class="card shadow-sm">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped text-center align-middle mb-0">
        <thead class="table-dark">
          <tr>
            <th>#</th>
            <th>الصندوق</th>
            <th>النوع</th>
            <th>الجهة</th>
            <th>المبلغ</th>
            <th>الملاحظة</th>
            <th>التاريخ</th>
            <th>إجراءات</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($logs as $r): ?>
          <tr>
            <td><?= $r['id'] ?></td>
            <td><?= htmlspecialchars($r['cashbox_name']) ?></td>
            <td class="<?= $r['type']=='add'?'text-success':'text-danger' ?>">
              <?= $r['type']=='add' ? 'إيداع' : 'سحب' ?>
            </td>
            <td>
              <?= htmlspecialchars($r['entity_name'] ?? '') ?>
              <?php if(!empty($r['entity_type'])): ?>
                <small class="text-muted">
                  (<?= $r['entity_type']=='customer'?'عميل':($r['entity_type']=='supplier'?'مورد':'مخلص') ?>)
                </small>
              <?php endif; ?>
            </td>
            <td><?= number_format($r['amount'],2) ?> ₺</td>
            <td><?= htmlspecialchars($r['note']) ?></td>
            <td><?= $r['date'] ?></td>
            <td>
              <form method="post" style="display:inline-block">
                <input type="hidden" name="id" value="<?= $r['id'] ?>">
                <input type="number" name="amount" value="<?= $r['amount'] ?>" step="0.01" style="width:80px" class="form-control d-inline">
                <input type="text" name="note" value="<?= htmlspecialchars($r['note']) ?>" style="width:120px" class="form-control d-inline">
                <button name="edit_transaction" class="btn btn-sm btn-outline-primary">💾</button>
              </form>
              <a href="?delete=<?= $r['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('هل تريد حذف هذه العملية؟')">🗑</a>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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