<?php
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'] ?? '';

// ACTION: TÌM NHÀ CUNG CẤP CHO DROPDOWN
if ($action == 'search_suppliers') {
    $search = $_GET['q'] ?? '';
    $sql = "SELECT ID, supplier_name, supplier_code FROM cms_suppliers WHERE supplier_name LIKE ? OR supplier_code LIKE ? 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 = [];
    foreach ($suppliers as $supplier) {
        $results[] = ['id' => $supplier['ID'], 'text' => $supplier['supplier_name'] . ' (' . $supplier['supplier_code'] . ')'];
    }
    echo json_encode(['results' => $results]);
    exit();
}

// ACTION: TÌM NHÂN VIÊN CHO DROPDOWN
if ($action == 'search_users') {
    $search = $_GET['q'] ?? '';
    $sql = "SELECT ID, display_name FROM cms_users WHERE display_name LIKE ? 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 = [];
    foreach ($users as $user) {
        $results[] = ['id' => $user['ID'], 'text' => $user['display_name']];
    }
    echo json_encode(['results' => $results]);
    exit();
}

// ACTION: LƯU PHIẾU CHI (THÊM & SỬA)
if ($action == 'save_payment') {
    $id = intval($_POST['id'] ?? 0);
    $notes = trim($_POST['notes'] ?? '');
    $type_id = intval($_POST['type_id'] ?? 0);
    $total_money = floatval($_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) {
        echo json_encode(['status' => 'error', 'message' => 'Vui lòng điền đầy đủ thông tin bắt buộc (Hình thức chi, Số tiền).']);
        exit();
    }

    // THAY ĐỔI TẠI ĐÂY: Khởi tạo payment_for = 0 để tránh lỗi NULL
    $payment_for = 0; 
    if (in_array($type_id, [1, 3])) { // Chi mua hàng, Chi nhập hàng
        $payment_for = !empty($_POST['supplier_id']) ? intval($_POST['supplier_id']) : 0;
    } elseif ($type_id == 2) { // Chi lương
        $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) { // Cập nhật
        $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 { // Thêm mới
        $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()) {
        echo json_encode(['status' => 'success', 'message' => 'Lưu phiếu chi thành công!']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Lỗi khi lưu: ' . ($stmt ? $stmt->error : $conn->error)]);
    }
    $stmt->close();
    exit();
}

// CÁC ACTION KHÁC GIỮ NGUYÊN
// ... (get_payment_details, delete_payment, get_payments)
if ($action == 'get_payment_details') {
    $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();
    echo json_encode(['status' => 'success', 'data' => $result]);
    exit();
}

if ($action == 'delete_payment') {
    $id = intval($_POST['id'] ?? 0);
    $stmt = $conn->prepare("UPDATE cms_payment SET deleted = 1 WHERE ID = ?");
    $stmt->bind_param('i', $id);
    if ($stmt->execute()) {
        echo json_encode(['status' => 'success', 'message' => 'Xóa phiếu chi thành công!']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Lỗi khi xóa.']);
    }
    exit();
}

if ($action == 'get_payments') {
    $draw = intval($_POST['draw'] ?? 0);
    $start = intval($_POST['start'] ?? 0);
    $length = intval($_POST['length'] ?? 10);
    $search = $_POST['search_term'] ?? '';

    $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($search)) {
        $whereClauses[] = "p.payment_code LIKE ?";
        $params[] = "%" . $search . "%";
        $types .= 's';
    }
    if (!empty($_POST['type_id'])) {
        $whereClauses[] = "p.type_id = ?";
        $params[] = $_POST['type_id'];
        $types .= 'i';
    }
    if (!empty($_POST['start_date']) && !empty($_POST['end_date'])) {
        $whereClauses[] = "DATE(p.payment_date) BETWEEN ? AND ?";
        $params[] = $_POST['start_date'];
        $params[] = $_POST['end_date'];
        $types .= 'ss';
    }

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

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

    $totalFilteredQuery = $conn->prepare("SELECT COUNT(p.ID) " . $baseQuery . $whereSql);
    if (!empty($types)) { $totalFilteredQuery->bind_param($types, ...$params); }
    $totalFilteredQuery->execute();
    $totalFiltered = $totalFilteredQuery->get_result()->fetch_row()[0];
    $totalFilteredQuery->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]);
    $dataStmt->bind_param($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();

    $sumQuery = $conn->prepare("SELECT SUM(p.total_money) as total_sum " . $baseQuery . $whereSql);
    if (!empty($types)) { $sumQuery->bind_param($types, ...$params); }
    $sumQuery->execute();
    $sumResult = $sumQuery->get_result()->fetch_assoc();
    $totalSum = $sumResult['total_sum'] ?? 0;
    $sumQuery->close();

    echo json_encode([
        "draw" => $draw,
        "recordsTotal" => intval($totalRecords),
        "recordsFiltered" => intval($totalFiltered),
        "data" => $data,
        "totalSum" => $totalSum
    ]);
    exit();
}

echo json_encode(['status' => 'error', 'message' => 'Hành động không hợp lệ.']);
$conn->close();
?>