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

/* ============================================================
   🧩 دالة جلب اسم الحساب حسب النوع
   ============================================================ */
function getNameByType($pdo, $type, $id) {

    if ($type === 'customer') {
        $q = $pdo->prepare("SELECT name FROM customers WHERE id=?");
    } elseif ($type === 'supplier') {
        $q = $pdo->prepare("SELECT name FROM suppliers WHERE id=?");
    } elseif ($type === 'agent') {
        $q = $pdo->prepare("SELECT name FROM agents WHERE id=?");
    } elseif ($type === 'cash') {
        $q = $pdo->prepare("SELECT name FROM cashbox WHERE id=?");
    } else {
        return 'غير محدد';
    }

    $q->execute([$id]);
    return $q->fetchColumn() ?: 'غير محدد';
}

/* ============================================================
   📋 جلب القوائم (عملاء / موردين / مخلصين / صناديق)
   ============================================================ */
$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 id,name FROM cashbox ORDER BY name")->fetchAll();

/* ============================================================
   ❌ حذف عملية تحويل وإلغاء أثرها بالكامل
   ============================================================ */
if (isset($_GET['delete'])) {

    $id = intval($_GET['delete']);
    $stmt = $pdo->prepare("SELECT * FROM transfers WHERE id=?");
    $stmt->execute([$id]);
    $tr = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($tr) {

        $from_type = $tr['from_type'];
        $from_id   = $tr['from_id'];
        $to_type   = $tr['to_type'];
        $to_id     = $tr['to_id'];
        $amount    = floatval($tr['amount']);

        $pdo->beginTransaction();
        try {

            /* ========== إزالة أثر المرسل ========== */
            if ($from_type === 'customer') {
                $pdo->prepare("DELETE FROM customer_money 
                               WHERE customer_id=? AND amount=? AND type='out' LIMIT 1")
                    ->execute([$from_id, $amount]);

            } elseif ($from_type === 'supplier') {
                $pdo->prepare("DELETE FROM supplier_money 
                               WHERE supplier_id=? AND amount=? AND type='out' LIMIT 1")
                    ->execute([$from_id, $amount]);

            } elseif ($from_type === 'agent') {
                $pdo->prepare("DELETE FROM agent_money 
                               WHERE agent_id=? AND amount=? AND type='out' LIMIT 1")
                    ->execute([$from_id, $amount]);

            } elseif ($from_type === 'cash') {
                $pdo->prepare("UPDATE cashbox SET balance = balance + ? WHERE id=?")
                    ->execute([$amount, $from_id]);

                $pdo->prepare("DELETE FROM cashbox_log 
                               WHERE cashbox_id=? AND amount=? AND type='withdraw' LIMIT 1")
                    ->execute([$from_id, $amount]);
            }

            /* ========== إزالة أثر المستلم ========== */
            if ($to_type === 'customer') {
                $pdo->prepare("DELETE FROM customer_money 
                               WHERE customer_id=? AND amount=? AND type='in' LIMIT 1")
                    ->execute([$to_id, $amount]);

            } elseif ($to_type === 'supplier') {
                $pdo->prepare("DELETE FROM supplier_money 
                               WHERE supplier_id=? AND amount=? AND type='in' LIMIT 1")
                    ->execute([$to_id, $amount]);

            } elseif ($to_type === 'agent') {
                $pdo->prepare("DELETE FROM agent_money 
                               WHERE agent_id=? AND amount=? AND type='in' LIMIT 1")
                    ->execute([$to_id, $amount]);

            } elseif ($to_type === 'cash') {
                $pdo->prepare("UPDATE cashbox SET balance = balance - ? WHERE id=?")
                    ->execute([$amount, $to_id]);

                $pdo->prepare("DELETE FROM cashbox_log 
                               WHERE cashbox_id=? AND amount=? AND type='add' LIMIT 1")
                    ->execute([$to_id, $amount]);
            }

            /* حذف سجل التحويل نفسه */
            $pdo->prepare("DELETE FROM transfers WHERE id=?")->execute([$id]);

            $pdo->commit();

            $_SESSION['flash_message'] = "✔️ تم حذف التحويل بالكامل وإلغاء أثره.";
            header("Location: transfers.php");
            exit;

        } catch (Exception $e) {
            $pdo->rollBack();
            echo "<div class='alert alert-danger text-center'>
                    خطأ أثناء الحذف: ".$e->getMessage()."
                  </div>";
        }
    }
}


    

/* ============================================================
   💸 تنفيذ عملية التحويل الجديدة
   ============================================================ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $from_type = $_POST['from_type'] ?? '';
    $from_id   = intval($_POST['from_id'] ?? 0);
    $to_type   = $_POST['to_type'] ?? '';
    $to_id     = intval($_POST['to_id'] ?? 0);
    $amount    = floatval($_POST['amount'] ?? 0);
    $note      = trim($_POST['note'] ?? '');
    $date      = $_POST['date'] ?: date('Y-m-d');

    // تحقق أساسي من صحة الإدخال
    if ($amount <= 0 || !$from_type || !$to_type || ($from_type === $to_type && $from_id === $to_id)) {
        echo "<div class='alert alert-danger text-center'>❌ بيانات غير مكتملة أو تحويل لنفس الحساب.</div>";
    } else {

        $from_name = getNameByType($pdo, $from_type, $from_id);
        $to_name   = getNameByType($pdo, $to_type, $to_id);

        $note_from = "تحويل إلى: $to_name - $note";
        $note_to   = "تحويل من: $from_name - $note";

        $pdo->beginTransaction();
        try {

            /* ========== خصم من المرسل (out) ========== */
            if ($from_type === 'customer') {
                $pdo->prepare("
                    INSERT INTO customer_money 
                    (customer_id,type,amount,date,note,payment_type)
                    VALUES (?,?,?,?,?,'تحويل')
                ")->execute([$from_id, 'out', $amount, $date, $note_from]);

            } elseif ($from_type === 'supplier') {
                $pdo->prepare("
                    INSERT INTO supplier_money 
                    (supplier_id,type,amount,date,note,payment_type)
                    VALUES (?,?,?,?,?,'تحويل')
                ")->execute([$from_id, 'out', $amount, $date, $note_from]);

            } elseif ($from_type === 'agent') {
                $pdo->prepare("
                    INSERT INTO agent_money 
                    (agent_id,type,amount,date,note,payment_type)
                    VALUES (?,?,?,?,?,'تحويل')
                ")->execute([$from_id, 'out', $amount, $date, $note_from]);

            } elseif ($from_type === 'cash') {
                // 💡 لا نمنع السالب هنا (كما قلت: السالب = دين)
                $pdo->prepare("UPDATE cashbox SET balance = balance - ? WHERE id=?")
                    ->execute([$amount, $from_id]);

                $pdo->prepare("
                    INSERT INTO cashbox_log (cashbox_id,type,amount,note,source)
                    VALUES (?,?,?,?,?)
                ")->execute([$from_id, 'withdraw', $amount, $note_from, 'transfer']);
            }

            /* ========== إضافة إلى المستلم (in) ========== */
            if ($to_type === 'customer') {
                $pdo->prepare("
                    INSERT INTO customer_money 
                    (customer_id,type,amount,date,note,payment_type)
                    VALUES (?,?,?,?,?,'تحويل')
                ")->execute([$to_id, 'in', $amount, $date, $note_to]);

            } elseif ($to_type === 'supplier') {
                $pdo->prepare("
                    INSERT INTO supplier_money 
                    (supplier_id,type,amount,date,note,payment_type)
                    VALUES (?,?,?,?,?,'تحويل')
                ")->execute([$to_id, 'in', $amount, $date, $note_to]);

            } elseif ($to_type === 'agent') {
                $pdo->prepare("
                    INSERT INTO agent_money 
                    (agent_id,type,amount,date,note,payment_type)
                    VALUES (?,?,?,?,?,'تحويل')
                ")->execute([$to_id, 'in', $amount, $date, $note_to]);

            } elseif ($to_type === 'cash') {
                $pdo->prepare("UPDATE cashbox SET balance = balance + ? WHERE id=?")
                    ->execute([$amount, $to_id]);

                $pdo->prepare("
                    INSERT INTO cashbox_log (cashbox_id,type,amount,note,source)
                    VALUES (?,?,?,?,?)
                ")->execute([$to_id, 'add', $amount, $note_to, 'transfer']);
            }

            /* ==== حفظ سجل التحويل الأساسي ==== */
            $pdo->prepare("
                INSERT INTO transfers
                (from_type,from_id,to_type,to_id,amount,note,date)
                VALUES (?,?,?,?,?,?,?)
            ")->execute([$from_type, $from_id, $to_type, $to_id, $amount, $note, $date]);

            $pdo->commit();

            $_SESSION['flash_message'] = "✔️ تم تنفيذ التحويل بنجاح.";
            header("Location: transfers.php");
            exit;

        } catch (Exception $e) {
            $pdo->rollBack();
            echo "<div class='alert alert-danger text-center'>خطأ أثناء التحويل: ".$e->getMessage()."</div>";
        }
    }
}

/* ============================================================
   📜 عرض سجل التحويلات
   ============================================================ */
$rows = $pdo->query("SELECT * FROM transfers ORDER BY id DESC")->fetchAll();
?>

<h3 class="mb-3 text-primary">🔄 التحويلات بين الحسابات</h3>

<?php 
if (isset($_SESSION['flash_message'])) {
    echo "<div class='alert alert-success'>".$_SESSION['flash_message']."</div>";
    unset($_SESSION['flash_message']);
}
?>

<div class="card shadow-sm mb-4">
    <div class="card-body">
        <form method="post" class="row g-3">

            <div class="col-md-3">
                <label class="form-label">من الحساب</label>
                <select class="form-select" name="from_type" id="from_type" required>
                    <option value="">— اختر —</option>
                    <option value="customer">عميل</option>
                    <option value="supplier">مورد</option>
                    <option value="agent">مخلص</option>
                    <option value="cash">صندوق</option>
                </select>
            </div>

            <div class="col-md-3" id="from_id_div">
                <label class="form-label">الاسم</label>
                <select class="form-select" name="from_id"></select>
            </div>

            <div class="col-md-3">
                <label class="form-label">إلى الحساب</label>
                <select class="form-select" name="to_type" id="to_type" required>
                    <option value="">— اختر —</option>
                    <option value="customer">عميل</option>
                    <option value="supplier">مورد</option>
                    <option value="agent">مخلص</option>
                    <option value="cash">صندوق</option>
                </select>
            </div>

            <div class="col-md-3" id="to_id_div">
                <label class="form-label">الاسم</label>
                <select class="form-select" name="to_id"></select>
            </div>

            <div class="col-md-4">
                <label class="form-label">المبلغ *</label>
                <input type="number" step="0.01" class="form-control" name="amount" required>
            </div>

            <div class="col-md-4">
                <label class="form-label">التاريخ</label>
                <input type="date" class="form-control" name="date" value="<?= date('Y-m-d') ?>">
            </div>

            <div class="col-md-4">
                <label class="form-label">ملاحظة</label>
                <input class="form-control" name="note">
            </div>

            <div class="col-12 text-end">
                <button class="btn btn-primary">💾 تنفيذ التحويل</button>
            </div>

        </form>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header bg-light fw-bold">📜 سجل التحويلات</div>
    <div class="card-body p-0">
        <table class="table table-striped text-center 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><?= getNameByType($pdo, $r['from_type'], $r['from_id']) ?></td>
                    <td><?= getNameByType($pdo, $r['to_type'], $r['to_id']) ?></td>
                    <td><?= number_format($r['amount'],2) ?></td>
                    <td><?= htmlspecialchars($r['note']) ?></td>
                    <td><?= $r['date'] ?></td>
                    <td>
                        <a href="?delete=<?= $r['id'] ?>"
                           class="btn btn-danger btn-sm"
                           onclick="return confirm('هل أنت متأكد من حذف العملية؟ سيتم عكس تأثيرها.');">
                           🗑 حذف
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
const customers = <?= json_encode($customers, JSON_UNESCAPED_UNICODE) ?>;
const suppliers = <?= json_encode($suppliers, JSON_UNESCAPED_UNICODE) ?>;
const agents    = <?= json_encode($agents, JSON_UNESCAPED_UNICODE) ?>;
const cashboxes = <?= json_encode($cashboxes, JSON_UNESCAPED_UNICODE) ?>;

function updateOptions(divId, type){
    const div = document.getElementById(divId);
    const select = div.querySelector('select');
    select.innerHTML = "";

    let list = [];

    if(type === 'customer') list = customers;
    else if(type === 'supplier') list = suppliers;
    else if(type === 'agent') list = agents;
    else if(type === 'cash') list = cashboxes;

    list.forEach(item =>{
        const opt = document.createElement("option");
        opt.value = item.id;
        opt.textContent = item.name;
        select.appendChild(opt);
    });
}

document.getElementById('from_type').addEventListener('change', ()=>{
    updateOptions('from_id_div', document.getElementById('from_type').value);
});

document.getElementById('to_type').addEventListener('change', ()=>{
    updateOptions('to_id_div', document.getElementById('to_type').value);
});
</script>

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