<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../core/init.php';
require_once __DIR__ . '/../includes/payment_helpers.php';

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

$action = $_REQUEST['action'] ?? '';

function json_error($message) {
    echo json_encode(['status' => 'error', 'message' => $message]);
    exit();
}
function json_success($message, $data = []) {
    $response = ['status' => 'success', 'message' => $message];
    if (!empty($data)) $response['data'] = $data;
    echo json_encode($response);
    exit();
}
function bind_dynamic_params($stmt, $types, &$params) {
    if (empty($types) || empty($params)) return;
    $refs = [];
    foreach ($params as $key => $value) $refs[$key] = &$params[$key];
    call_user_func_array([$stmt, 'bind_param'], array_merge([$types], $refs));
}

switch ($action) {
    case 'get_payments': handle_get_payments($conn); break;
    case 'save_payment': handle_save_payment($conn); break;
    case 'get_payment_details': handle_get_payment_details($conn); break;
    case 'delete_payment': handle_delete_payment($conn); break;
    case 'search_suppliers': handle_search_suppliers($conn); break;
    case 'search_users': handle_search_users($conn); break;
    case 'add_payment_type': handle_add_payment_type($conn); break;
    default: json_error('Hành động không hợp lệ.');
}

function handle_get_payments($conn) {
    $draw = intval($_POST['draw'] ?? 0);
    $start = intval($_POST['start'] ?? 0);
    $length = intval($_POST['length'] ?? 10);
    
    $payee_case_sql = "CASE WHEN p.type_id = 2 THEN u_payee.display_name WHEN p.type_id IN (1, 3) THEN s_payee.supplier_name ELSE '' END";
    $baseQuery = "FROM cms_payment p 
                    LEFT JOIN cms_users u_creator ON p.user_init = u_creator.ID 
                    LEFT JOIN cms_stores st ON p.store_id = st.ID
                    LEFT JOIN cms_suppliers s_payee ON p.payment_for = s_payee.ID AND p.type_id IN (1, 3)
                    LEFT JOIN cms_users u_payee ON p.payment_for = u_payee.ID AND p.type_id = 2";
    
    $whereClauses = ["p.deleted = 0"];
    $params = [];
    $types = '';

    if (!empty($_POST['search_term'])) {
        $whereClauses[] = "(p.payment_code LIKE ? OR p.notes LIKE ?)";
        $searchTerm = "%" . $_POST['search_term'] . "%";
        array_push($params, $searchTerm, $searchTerm);
        $types .= 'ss';
    }
    if (!empty($_POST['type_id'])) {
        $whereClauses[] = "p.type_id = ?"; $params[] = $_POST['type_id']; $types .= 'i';
    }
    if (!empty($_POST['start_date'])) {
        $whereClauses[] = "DATE(p.payment_date) >= ?"; $params[] = $_POST['start_date']; $types .= 's';
    }
    if (!empty($_POST['end_date'])) {
        $whereClauses[] = "DATE(p.payment_date) <= ?"; $params[] = $_POST['end_date']; $types .= 's';
    }

    $whereSql = " WHERE " . implode(" AND ", $whereClauses);

    $summaryQuery = "SELECT 
                        COUNT(p.id) as total_payments,
                        SUM(p.total_money) as total_amount,
                        SUM(CASE WHEN DATE(p.payment_date) = CURDATE() THEN p.total_money ELSE 0 END) as today_amount
                       {$baseQuery} {$whereSql}";
    $stmtSummary = $conn->prepare($summaryQuery);
    bind_dynamic_params($stmtSummary, $types, $params);
    $stmtSummary->execute();
    $summary_data = $stmtSummary->get_result()->fetch_assoc();
    $stmtSummary->close();

    $totalRecords = $conn->query("SELECT COUNT(ID) FROM cms_payment WHERE deleted = 0")->fetch_row()[0] ?? 0;

    $stmtFiltered = $conn->prepare("SELECT COUNT(p.ID) {$baseQuery} {$whereSql}");
    bind_dynamic_params($stmtFiltered, $types, $params);
    $stmtFiltered->execute();
    $totalFiltered = $stmtFiltered->get_result()->fetch_row()[0];
    $stmtFiltered->close();
    
    $dataQuery = "SELECT p.ID, p.payment_code, p.payment_image, st.store_name, p.payment_date, u_creator.display_name as creator_name, p.notes, p.type_id, p.total_money, ({$payee_case_sql}) as payee_name 
                    {$baseQuery} {$whereSql} ORDER BY p.ID DESC LIMIT ?, ?";
    $dataStmt = $conn->prepare($dataQuery);
    $data_types = $types . 'ii';
    $data_params = array_merge($params, [$start, $length]);
    bind_dynamic_params($dataStmt, $data_types, $data_params);
    $dataStmt->execute();
    $result = $dataStmt->get_result();
    
    $data = [];
    $payment_types = get_payment_types();
    while ($row = $result->fetch_assoc()) {
        $row['type_name'] = $payment_types[$row['type_id']] ?? 'Không xác định';
        $data[] = $row;
    }
    $dataStmt->close();

    echo json_encode([
        "draw" => $draw,
        "recordsTotal" => intval($totalRecords),
        "recordsFiltered" => intval($totalFiltered),
        "data" => $data,
        "totalSum" => $summary_data['total_amount'] ?? 0,
        "summary" => $summary_data
    ]);
}

function handle_save_payment($conn) {
    $id = intval($_POST['id'] ?? 0);
    $notes = trim($_POST['notes'] ?? '');
    $type_id = intval($_POST['type_id'] ?? 0);
    $total_money = floatval(str_replace('.', '', $_POST['total_money'] ?? '0'));
    $payment_date = $_POST['payment_date'] ?? date('Y-m-d H:i:s');
    $user_id = $_SESSION['user_id'] ?? 0;
    $store_id = 1;

    if ($total_money <= 0 || $type_id == 0) json_error('Vui lòng điền đầy đủ Hình thức chi và Số tiền.');

    $payment_for = 0; 
    if (in_array($type_id, [1, 3])) { $payment_for = !empty($_POST['supplier_id']) ? intval($_POST['supplier_id']) : 0; }
    elseif ($type_id == 2) { $payment_for = !empty($_POST['pay_to_user_id']) ? intval($_POST['pay_to_user_id']) : 0; }

    $image_path = $_POST['current_image'] ?? '';
    if (isset($_FILES['payment_image']) && $_FILES['payment_image']['error'] == 0) {
        $target_dir = __DIR__ . "/../../uploads/payments/";
        if (!is_dir($target_dir)) { mkdir($target_dir, 0755, true); }
        $file_name = time() . '_' . basename($_FILES["payment_image"]["name"]);
        $target_file = $target_dir . $file_name;
        if (move_uploaded_file($_FILES["payment_image"]["tmp_name"], $target_file)) {
            $image_path = 'uploads/payments/' . $file_name;
        }
    }

    if ($id > 0) {
        $sql = "UPDATE cms_payment SET notes=?, type_id=?, total_money=?, payment_date=?, payment_for=?, payment_image=?, user_upd=? WHERE ID=?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('sidssiii', $notes, $type_id, $total_money, $payment_date, $payment_for, $image_path, $user_id, $id);
    } else {
        $last_id_result = $conn->query("SELECT ID FROM cms_payment ORDER BY ID DESC LIMIT 1");
        $last_id = $last_id_result ? $last_id_result->fetch_row()[0] : 0;
        $payment_code = 'PC' . str_pad($last_id + 1, 7, '0', STR_PAD_LEFT);
        
        $sql = "INSERT INTO cms_payment (payment_code, notes, type_id, total_money, payment_date, payment_for, payment_image, store_id, user_init) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('ssidsisii', $payment_code, $notes, $type_id, $total_money, $payment_date, $payment_for, $image_path, $store_id, $user_id);
    }

    if ($stmt && $stmt->execute()) {
        json_success('Lưu phiếu chi thành công!');
    } else {
        json_error('Lỗi khi lưu: ' . ($stmt ? $stmt->error : $conn->error));
    }
    $stmt->close();
}

function handle_get_payment_details($conn) {
    $id = intval($_GET['id'] ?? 0);
    $sql = "SELECT p.*, s.supplier_name, u_payee.display_name as payee_user_name
            FROM cms_payment p
            LEFT JOIN cms_suppliers s ON p.payment_for = s.ID AND p.type_id IN (1, 3)
            LEFT JOIN cms_users u_payee ON p.payment_for = u_payee.ID AND p.type_id = 2
            WHERE p.ID = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    json_success('Lấy chi tiết thành công.', $result);
}

function handle_delete_payment($conn) {
    $id = intval($_POST['id'] ?? 0);
    if ($id <= 0) json_error('ID không hợp lệ.');
    $stmt = $conn->prepare("UPDATE cms_payment SET deleted = 1 WHERE ID = ?");
    $stmt->bind_param('i', $id);
    if ($stmt->execute()) {
        json_success('Xóa phiếu chi thành công!');
    } else {
        json_error('Lỗi khi xóa.');
    }
}

function handle_add_payment_type($conn) {
    $name = trim($_POST['name'] ?? '');
    if (empty($name)) {
        json_error('Tên hình thức chi không được để trống.');
    }
    $sql = "INSERT INTO cms_payment_types (name) VALUES (?)";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        json_error('Lỗi khi chuẩn bị câu lệnh: ' . $conn->error);
    }
    $stmt->bind_param('s', $name);
    if ($stmt->execute()) {
        $new_id = $conn->insert_id;
        json_success('Thêm hình thức chi thành công!', ['id' => $new_id, 'name' => $name]);
    } else {
        json_error('Không thể lưu vào cơ sở dữ liệu: ' . $stmt->error);
    }
    $stmt->close();
}

function handle_search_suppliers($conn) {
    $search = $_GET['q'] ?? '';
    $sql = "SELECT ID, supplier_name, supplier_code FROM cms_suppliers WHERE (supplier_name LIKE ? OR supplier_code LIKE ?) AND deleted = 0 LIMIT 20";
    $stmt = $conn->prepare($sql);
    $searchTerm = "%" . $search . "%";
    $stmt->bind_param('ss', $searchTerm, $searchTerm);
    $stmt->execute();
    $suppliers = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    $results = array_map(function($s) {
        return ['id' => $s['ID'], 'text' => $s['supplier_name'] . ' (' . $s['supplier_code'] . ')'];
    }, $suppliers);
    
    echo json_encode(['results' => $results]);
}

function handle_search_users($conn) {
    $search = $_GET['q'] ?? '';
    $sql = "SELECT ID, display_name FROM cms_users WHERE display_name LIKE ? AND user_status = 1 LIMIT 20";
    $stmt = $conn->prepare($sql);
    $searchTerm = "%" . $search . "%";
    $stmt->bind_param('s', $searchTerm);
    $stmt->execute();
    $users = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    $results = array_map(function($u) {
        return ['id' => $u['ID'], 'text' => $u['display_name']];
    }, $users);

    echo json_encode(['results' => $results]);
}

$conn->close();
?>