<?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_money'])) {
  $entity_type = $_POST['entity_type']; // customer / supplier / agent
  $entity_id   = (int)$_POST['entity_id'];
  $amount      = (float)$_POST['amount'];
  $date        = $_POST['date'] ?: date('Y-m-d');
  $note        = trim($_POST['note']);
  $payment_type= $_POST['payment_type'];
  $cashbox_id  = (int)$_POST['cashbox_id'];

  if ($amount > 0) {
    if ($entity_type === 'customer') {
      $pdo->prepare("INSERT INTO customer_money (customer_id,type,amount,date,note,payment_type,cashbox_id)
                     VALUES (?,?,?,?,?,?,?)")->execute([$entity_id,'in',$amount,$date,$note,$payment_type,$cashbox_id]);
    } elseif ($entity_type === 'supplier') {
      $pdo->prepare("INSERT INTO supplier_money (supplier_id,type,amount,date,note,payment_type,cashbox_id)
                     VALUES (?,?,?,?,?,?,?)")->execute([$entity_id,'in',$amount,$date,$note,$payment_type,$cashbox_id]);
    } elseif ($entity_type === 'agent') {
      $pdo->prepare("INSERT INTO agent_money (agent_id,type,amount,date,note,payment_type,cashbox_id)
                     VALUES (?,?,?,?,?,?,?)")->execute([$entity_id,'in',$amount,$date,$note,$payment_type,$cashbox_id]);
    }

    if ($payment_type === 'كاش') {
      $pdo->prepare("UPDATE cashbox SET balance = balance + ? WHERE id=?")->execute([$amount, $cashbox_id]);
      $pdo->prepare("INSERT INTO cashbox_log (cashbox_id,type,amount,note,date)
                     VALUES (?,?,?,?,?)")->execute([$cashbox_id,'add',$amount,"قبض من {$entity_type} رقم {$entity_id}",$date]);
    }
  }

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

/* -------------------- تعديل -------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_money'])) {
  $table = $_POST['table_name'];
  $id    = (int)$_POST['id'];

  $old = $pdo->prepare("SELECT * FROM {$table} WHERE id=?");
  $old->execute([$id]);
  $oldData = $old->fetch();

  if ($oldData) {
    $amount = (float)$_POST['amount'];
    $date   = $_POST['date'];
    $note   = trim($_POST['note']);
    $payment_type = $_POST['payment_type'];

    // عكس العملية القديمة من الصندوق إن كانت كاش
    if ($oldData['payment_type'] === 'كاش') {
      $pdo->prepare("UPDATE cashbox SET balance = balance - ? WHERE id=?")->execute([$oldData['amount'], $oldData['cashbox_id']]);
    }

    // تحديث البيانات
    $pdo->prepare("UPDATE {$table} SET amount=?, date=?, note=?, payment_type=? WHERE id=?")
        ->execute([$amount, $date, $note, $payment_type, $id]);

    // تطبيق التعديل الجديد
    if ($payment_type === 'كاش') {
      $pdo->prepare("UPDATE cashbox SET balance = balance + ? WHERE id=?")->execute([$amount, $oldData['cashbox_id']]);
      $pdo->prepare("INSERT INTO cashbox_log (cashbox_id,type,amount,note,date)
                     VALUES (?,?,?,?,?)")->execute([$oldData['cashbox_id'],'adjust',$amount,"تعديل قبض {$table} رقم {$id}",$date]);
    }
  }

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

/* -------------------- حذف -------------------- */
if (isset($_GET['delete']) && isset($_GET['table'])) {
  $id = (int)$_GET['delete'];
  $table = $_GET['table'];

  $stmt = $pdo->prepare("SELECT * FROM {$table} WHERE id=?");
  $stmt->execute([$id]);
  $data = $stmt->fetch();

  if ($data && $data['payment_type'] === 'كاش') {
    $pdo->prepare("UPDATE cashbox SET balance = balance - ? WHERE id=?")->execute([$data['amount'], $data['cashbox_id']]);
    $pdo->prepare("INSERT INTO cashbox_log (cashbox_id,type,amount,note,date)
                   VALUES (?,?,?,?,?)")->execute([$data['cashbox_id'],'reverse',$data['amount'],"إلغاء قبض {$table} رقم {$id}",$data['date']]);
  }

  $pdo->prepare("DELETE FROM {$table} WHERE id=?")->execute([$id]);
  header("Location: money.php");
  exit;
}

/* -------------------- جلب القوائم -------------------- */
$customers = $pdo->query("SELECT id,name FROM customers ORDER BY name")->fetchAll();
$suppliers = $pdo->query("SELECT id,name FROM suppliers ORDER BY name")->fetchAll();
$agents    = $pdo->query("SELECT id,name FROM agents ORDER BY name")->fetchAll();
$cashboxes = $pdo->query("SELECT * FROM cashbox ORDER BY id")->fetchAll();

/* -------------------- جلب كل العمليات -------------------- */
function getAllMovements($pdo) {
  $sql_customer = "SELECT 'customer_money' AS table_name, cm.id, 'عميل' AS entity_type, c.name AS entity_name,
                   cm.amount, cm.date, cm.note, cm.payment_type, cb.name AS cashbox_name
                   FROM customer_money cm
                   LEFT JOIN customers c ON c.id=cm.customer_id
                   LEFT JOIN cashbox cb ON cb.id=cm.cashbox_id
                   WHERE cm.type='in'";
  $sql_supplier = "SELECT 'supplier_money' AS table_name, sm.id, 'مورد' AS entity_type, s.name AS entity_name,
                   sm.amount, sm.date, sm.note, sm.payment_type, cb.name AS cashbox_name
                   FROM supplier_money sm
                   LEFT JOIN suppliers s ON s.id=sm.supplier_id
                   LEFT JOIN cashbox cb ON cb.id=sm.cashbox_id
                   WHERE sm.type='in'";
  $sql_agent = "SELECT 'agent_money' AS table_name, am.id, 'مخلص' AS entity_type, a.name AS entity_name,
                am.amount, am.date, am.note, am.payment_type, cb.name AS cashbox_name
                FROM agent_money am
                LEFT JOIN agents a ON a.id=am.agent_id
                LEFT JOIN cashbox cb ON cb.id=am.cashbox_id
                WHERE am.type='in'";

  $union = "$sql_customer UNION ALL $sql_supplier UNION ALL $sql_agent ORDER BY date DESC, id DESC";
  return $pdo->query($union)->fetchAll();
}

$rows = getAllMovements($pdo);
?>

<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 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>
            <th>إجراءات</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach($rows as $r): ?>
          <tr>
            <td><?= $r['id'] ?></td>
            <td><?= htmlspecialchars($r['entity_type'] ?? '') ?></td>
            <td><?= htmlspecialchars($r['entity_name'] ?? '') ?></td>
            <td><?= number_format($r['amount'],2) ?></td>
            <td><?= htmlspecialchars($r['payment_type'] ?? '') ?></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="<?= htmlspecialchars($r['date'] ?? '') ?>"
                data-note="<?= htmlspecialchars($r['note'] ?? '') ?>"
                data-type="<?= htmlspecialchars($r['payment_type'] ?? '') ?>"
                data-table="<?= htmlspecialchars($r['table_name'] ?? '') ?>">✏️ تعديل</button>
              <a href="?delete=<?= $r['id'] ?>&table=<?= htmlspecialchars($r['table_name'] ?? '') ?>"
                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 modal-lg">
    <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-md-4">
          <label class="form-label">نوع الجهة</label>
          <select name="entity_type" id="entity_type" class="form-select" onchange="updateEntityList()">
            <option value="customer">عميل</option>
            <option value="supplier">مورد</option>
            <option value="agent">مخلص</option>
          </select>
        </div>
        <div class="col-md-8">
          <label class="form-label">الاسم</label>
          <select name="entity_id" id="entity_select" class="form-select"></select>
        </div>
        <div class="col-md-4">
          <label class="form-label">المبلغ</label>
          <input type="number" step="0.01" name="amount" class="form-control" required>
        </div>
        <div class="col-md-4">
          <label class="form-label">التاريخ</label>
          <input type="date" name="date" class="form-control" value="<?= date('Y-m-d') ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">طريقة الدفع</label>
          <select name="payment_type" class="form-select">
            <option value="كاش">كاش</option>
            <option value="تحويل">تحويل</option>
          </select>
        </div>
        <div class="col-md-6">
          <label class="form-label">الصندوق</label>
          <select name="cashbox_id" class="form-select">
            <?php foreach($cashboxes as $cb): ?>
              <option value="<?= $cb['id'] ?>"><?= htmlspecialchars($cb['name'] ?? '') ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-6">
          <label class="form-label">ملاحظة</label>
          <input name="note" class="form-control">
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-success" name="add_money">💾 حفظ</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">
      <input type="hidden" name="table_name" id="edit_table">
      <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>
          <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>
          <select class="form-select" name="payment_type" id="edit_type">
            <option value="كاش">كاش</option>
            <option value="تحويل">تحويل</option>
          </select>
        </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_money">💾 حفظ التعديلات</button>
      </div>
    </form>
  </div>
</div>

<script>
const lists = {
  customer: <?= json_encode($customers) ?>,
  supplier: <?= json_encode($suppliers) ?>,
  agent: <?= json_encode($agents) ?>
};
function updateEntityList(){
  const type=document.getElementById('entity_type').value;
  const sel=document.getElementById('entity_select');
  sel.innerHTML='';
  lists[type].forEach(x=>{
    let opt=document.createElement('option');
    opt.value=x.id;
    opt.textContent=x.name;
    sel.appendChild(opt);
  });
}
updateEntityList();

var editModal=document.getElementById('editModal');
editModal.addEventListener('show.bs.modal',function(e){
  let b=e.relatedTarget;
  document.getElementById('edit_id').value=b.dataset.id;
  document.getElementById('edit_table').value=b.dataset.table;
  document.getElementById('edit_amount').value=b.dataset.amount;
  document.getElementById('edit_date').value=b.dataset.date;
  document.getElementById('edit_note').value=b.dataset.note;
  document.getElementById('edit_type').value=b.dataset.type;
});
</script>

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