<?php
// ajax/payments_ajax.php
ini_set('display_errors', 0);
error_reporting(E_ALL);
require_once __DIR__ . '/../core/init.php';
require_once __DIR__ . '/../includes/payment_helpers.php'; // Nơi chứa hàm cms_add_ledger nếu có

header('Content-Type: application/json; charset=utf-8');
if (session_status() == PHP_SESSION_NONE) { session_start(); }

$action = $_REQUEST['action'] ?? '';
$store_id = $_SESSION['store_id'] ?? 1;
$user_id = $_SESSION['user_id'] ?? 0;

switch ($action) {
    case 'get_payments': handle_get_payments($conn); break;
    case 'save_payment': handle_save_payment($conn, $store_id, $user_id); break;
    case 'get_detail': handle_get_detail($conn); break;
    case 'delete_payment': handle_delete_payment($conn); break;
    default: echo json_encode(['status' => 'error', 'message' => 'Action invalid']);
}

function handle_get_payments($conn) {
    $start = intval($_POST['start'] ?? 0);
    $length = intval($_POST['length'] ?? 10);
    
    $where = ["p.deleted = 0"];
    
    if (!empty($_POST['search_term'])) {
        $term = $conn->real_escape_string($_POST['search_term']);
        $where[] = "(p.payment_code LIKE '%$term%' OR p.notes LIKE '%$term%')";
    }
    if (!empty($_POST['type_id'])) $where[] = "p.type_id = " . intval($_POST['type_id']);
    if (!empty($_POST['start_date'])) $where[] = "DATE(p.payment_date) >= '{$_POST['start_date']}'";
    if (!empty($_POST['end_date'])) $where[] = "DATE(p.payment_date) <= '{$_POST['end_date']}'";
    
    $where_sql = implode(" AND ", $where);

    // Summary
    $summary = $conn->query("SELECT count(*) as total_payments, sum(total_money) as total_amount FROM cms_payment p WHERE $where_sql")->fetch_assoc();
    $today_sum = $conn->query("SELECT sum(total_money) FROM cms_payment p WHERE deleted=0 AND DATE(payment_date) = CURDATE()")->fetch_row()[0] ?? 0;
    
    // Data
    $sql = "SELECT p.*, u.display_name as creator_name, t.type_name 
            FROM cms_payment p 
            LEFT JOIN cms_users u ON p.user_init = u.id 
            LEFT JOIN cms_payment_type t ON p.type_id = t.id 
            WHERE $where_sql 
            ORDER BY p.payment_date DESC LIMIT $start, $length";
            
    $data = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);
    
    echo json_encode([
        "draw" => intval($_POST['draw'] ?? 0),
        "recordsTotal" => $summary['total_payments'],
        "recordsFiltered" => $summary['total_payments'],
        "data" => $data,
        "totalSum" => $summary['total_amount'] ?? 0,
        "summary" => [
            "total_payments" => $summary['total_payments'],
            "total_amount" => $summary['total_amount'] ?? 0,
            "today_amount" => $today_sum
        ]
    ]);
}

function handle_save_payment($conn, $store_id, $user_id) {
    $id = intval($_POST['id'] ?? 0);
    $total_money = floatval($_POST['total_money']);
    $type_id = intval($_POST['type_id']);
    $notes = trim($_POST['notes']);
    $payment_date = $_POST['payment_date'];

    if ($total_money <= 0) { echo json_encode(['status'=>'error','message'=>'Số tiền không hợp lệ']); exit; }

    if ($id > 0) {
        // Update
        $stmt = $conn->prepare("UPDATE cms_payment SET total_money=?, type_id=?, notes=?, payment_date=?, user_upd=? WHERE id=?");
        $stmt->bind_param("disssi", $total_money, $type_id, $notes, $payment_date, $user_id, $id);
        $stmt->execute();
        
        // Cập nhật sổ cái (Xóa cũ thêm mới hoặc update)
        // Đơn giản nhất: Xóa dòng ledger cũ, insert lại
        $conn->query("DELETE FROM cms_ledger WHERE source_type='PAYMENT' AND ref_id=$id");
        $ledger_note = "Cập nhật phiếu chi: $notes";
    } else {
        // Insert
        $res = $conn->query("SELECT id FROM cms_payment ORDER BY id DESC LIMIT 1");
        $last = ($res->fetch_row()[0] ?? 0) + 1;
        $code = 'PC' . str_pad($last, 6, '0', STR_PAD_LEFT);
        
        $stmt = $conn->prepare("INSERT INTO cms_payment (payment_code, total_money, type_id, notes, payment_date, store_id, user_init, created) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
        $stmt->bind_param("sdisiis", $code, $total_money, $type_id, $notes, $payment_date, $store_id, $user_id);
        $stmt->execute();
        $id = $conn->insert_id;
        $ledger_note = "Phiếu chi: $code - $notes";
    }

    // --- GHI SỔ CÁI (QUAN TRỌNG) ---
    // amount_out = Chi tiền
    if(function_exists('cms_add_ledger')) {
        cms_add_ledger($store_id, 'PAYMENT', $id, 0, $total_money, 0, $ledger_note);
    } else {
        // Fallback thủ công
        $conn->query("INSERT INTO cms_ledger (store_id, source_type, ref_id, amount_in, amount_out, cogs, note, transaction_date) 
                      VALUES ($store_id, 'PAYMENT', $id, 0, $total_money, 0, '$ledger_note', '$payment_date')");
    }

    echo json_encode(['status' => 'success', 'message' => 'Lưu thành công!']);
}

function handle_get_detail($conn) {
    $id = intval($_GET['id']);
    $data = $conn->query("SELECT * FROM cms_payment WHERE id=$id")->fetch_assoc();
    echo json_encode(['status'=>'success', 'data'=>$data]);
}

function handle_delete_payment($conn) {
    $id = intval($_POST['id']);
    $conn->query("UPDATE cms_payment SET deleted=1 WHERE id=$id");
    // Xóa khỏi sổ cái để hoàn lại tiền vào báo cáo
    $conn->query("DELETE FROM cms_ledger WHERE source_type='PAYMENT' AND ref_id=$id");
    echo json_encode(['status'=>'success', 'message'=>'Đã xóa phiếu chi']);
}
?>