<?php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $customer_id = intval($_POST['customer_id']);
    $type = $_POST['type'];
    $amount = floatval($_POST['amount']);
    $note = trim($_POST['note'] ?? '');

    if ($customer_id && $amount > 0 && in_array($type, ['debt','payment'])) {
        // أضف العملية إلى جدول customer_transactions
        $stmt = $pdo->prepare("
            INSERT INTO customer_transactions (customer_id, type, amount, note, date)
            VALUES (:cid, :type, :amount, :note, NOW())
        ");
        $stmt->execute([
            ':cid' => $customer_id,
            ':type' => $type,
            ':amount' => $amount,
            ':note' => $note
        ]);

        // تحديث الرصيد في جدول customers
        $update = $pdo->prepare("
            UPDATE customers c
            SET c.balance = (
                SELECT 
                    COALESCE(SUM(CASE WHEN t.type='debt' THEN t.amount ELSE 0 END),0)
                    - COALESCE(SUM(CASE WHEN t.type='payment' THEN t.amount ELSE 0 END),0)
                FROM customer_transactions t
                WHERE t.customer_id = c.id
            )
            WHERE c.id = :cid
        ");
        $update->execute([':cid' => $customer_id]);
    }
}

header("Location: debts.php?msg=done");
exit;
