<?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_expense'])) {
    $category   = $_POST['category'];
    $amount     = (float)$_POST['amount'];
    $date       = $_POST['date'] ?: date('Y-m-d');
    $note       = trim($_POST['note']);
    $cashbox_id = (int)$_POST['cashbox_id'];

    if ($amount > 0) {
        $pdo->prepare("INSERT INTO expenses (category, amount, date, note, cashbox_id) VALUES (?,?,?,?,?)")
            ->execute([$category, $amount, $date, $note, $cashbox_id]);

        // خصم من الصندوق
        $pdo->prepare("UPDATE cashbox SET balance = balance - ? WHERE id=?")->execute([$amount, $cashbox_id]);

        // سجل العملية
        $pdo->prepare("INSERT INTO cashbox_log (cashbox_id, type, amount, note) VALUES (?,?,?,?)")
            ->execute([$cashbox_id, 'withdraw', $amount, 'مصروف '.$category]);
    }

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

// -------------------- تعديل مصروف --------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_expense'])) {
    $id      = (int)$_POST['id'];
    $amount  = (float)$_POST['amount'];
    $date    = $_POST['date'];
    $note    = trim($_POST['note']);
    $category = $_POST['category'];

    $pdo->prepare("UPDATE expenses SET amount=?, date=?, note=?, category=? WHERE id=?")
        ->execute([$amount, $date, $note, $category, $id]);

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

// -------------------- حذف مصروف --------------------
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $pdo->prepare("DELETE FROM expenses WHERE id=?")->execute([$id]);
    header("Location: expenses.php");
    exit;
}

// -------------------- جلب البيانات --------------------
$cashboxes = $pdo->query("SELECT * FROM cashbox ORDER BY id ASC")->fetchAll();
$rows = $pdo->query("
    SELECT e.*, c.name AS cashbox_name 
    FROM expenses e
    JOIN cashbox c ON c.id = e.cashbox_id
    ORDER BY e.id DESC
")->fetchAll();
?>

<h3 class="mb-3 text-primary">💼 إدارة المصاريف</h3>

<div class="d-flex justify-content-end mb-3">
  <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addModal">➕ إضافة مصروف</button>
</div>

<div class="card shadow-sm">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped table-hover 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>
          </tr>
        </thead>
        <tbody>
        <?php foreach($rows as $r): ?>
          <tr>
            <td><?= $r['id'] ?></td>
            <td><?= htmlspecialchars($r['category']) ?></td>
            <td><?= number_format($r['amount'],2,'.',',') ?> $</td>
            <td><?= htmlspecialchars($r['cashbox_name']) ?></td>
            <td><?= htmlspecialchars($r['date']) ?></td>
            <td><?= htmlspecialchars($r['note']) ?></td>
            <td>
              <button class="btn btn-sm btn-outline-primary"
                      data-bs-toggle="modal"
                      data-bs-target="#editModal"
                      data-id="<?= $r['id'] ?>"
                      data-amount="<?= $r['amount'] ?>"
                      data-date="<?= $r['date'] ?>"
                      data-note="<?= htmlspecialchars($r['note']) ?>"
                      data-category="<?= htmlspecialchars($r['category']) ?>">
                      ✏️ تعديل
              </button>
              <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>

<!-- نافذة الإضافة -->
<div class="modal fade" id="addModal" tabindex="-1">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title">إضافة مصروف جديد</h5>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body row g-3">
        <div class="col-6">
          <label class="form-label">الفئة</label>
          <select class="form-select" name="category" required>
            <option value="نقل">مصاريف نقل</option>
            <option value="تخليص">مصاريف تخليص</option>
            <option value="أخرى">مصاريف أخرى</option>
          </select>
        </div>
        <div class="col-6">
          <label class="form-label">المبلغ *</label>
          <input type="number" step="0.01" class="form-control" name="amount" required>
        </div>
        <div class="col-6">
          <label class="form-label">التاريخ</label>
          <input type="date" class="form-control" name="date" value="<?= date('Y-m-d') ?>">
        </div>
        <div class="col-6">
          <label class="form-label">الصندوق</label>
          <select class="form-select" name="cashbox_id">
            <?php foreach($cashboxes as $cb): ?>
              <option value="<?= $cb['id'] ?>"><?= htmlspecialchars($cb['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-12">
          <label class="form-label">ملاحظة</label>
          <input class="form-control" name="note">
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-success" name="add_expense">💾 حفظ</button>
      </div>
    </form>
  </div>
</div>

<!-- نافذة التعديل -->
<div class="modal fade" id="editModal" tabindex="-1">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <input type="hidden" name="id" id="edit_id">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">تعديل المصروف</h5>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body row g-3">
        <div class="col-6">
          <label class="form-label">الفئة</label>
          <select class="form-select" name="category" id="edit_category">
            <option value="نقل">مصاريف نقل</option>
            <option value="تخليص">مصاريف تخليص</option>
            <option value="أخرى">مصاريف أخرى</option>
          </select>
        </div>
        <div class="col-6">
          <label class="form-label">المبلغ *</label>
          <input type="number" step="0.01" class="form-control" name="amount" id="edit_amount" required>
        </div>
        <div class="col-6">
          <label class="form-label">التاريخ</label>
          <input type="date" class="form-control" name="date" id="edit_date" required>
        </div>
        <div class="col-12">
          <label class="form-label">ملاحظة</label>
          <input class="form-control" name="note" id="edit_note">
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" name="edit_expense">💾 حفظ التعديلات</button>
      </div>
    </form>
  </div>
</div>

<script>
// تمرير بيانات المصروف إلى نافذة التعديل
var editModal = document.getElementById('editModal');
editModal.addEventListener('show.bs.modal', function (event) {
  var button = event.relatedTarget;
  document.getElementById('edit_id').value = button.getAttribute('data-id');
  document.getElementById('edit_amount').value = button.getAttribute('data-amount');
  document.getElementById('edit_date').value = button.getAttribute('data-date');
  document.getElementById('edit_note').value = button.getAttribute('data-note');
  document.getElementById('edit_category').value = button.getAttribute('data-category');
});
</script>

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