<?php
require_once __DIR__ . '/../core/init.php';

header('Content-Type: application/json; charset=utf-8');

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

$action = trim($_REQUEST['action'] ?? '');
$user_id = $_SESSION['user_id'] ?? 0;

// --- 1. SEARCH NHÀ CUNG CẤP (CHO AUTOCOMPLETE) ---
// ĐÂY LÀ PHẦN BỔ SUNG QUAN TRỌNG ĐỂ SỬA LỖI CỦA BẠN
function handle_search_suppliers($conn) {
    $term = trim($_REQUEST['term'] ?? '');
    $data = [];
    
    if (strlen($term) > 0) {
        // Tìm theo Tên, Mã hoặc SĐT
        $sql = "SELECT ID, supplier_name, supplier_code, supplier_phone 
                FROM cms_suppliers 
                WHERE supplier_name LIKE ? OR supplier_code LIKE ? OR supplier_phone LIKE ? 
                LIMIT 10";
        
        $stmt = $conn->prepare($sql);
        $likeTerm = "%$term%";
        $stmt->bind_param("sss", $likeTerm, $likeTerm, $likeTerm);
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $data[] = [
                'id' => $row['ID'],
                'name' => $row['supplier_name'],
                'code' => $row['supplier_code'],
                'phone' => $row['supplier_phone']
            ];
        }
    }
    echo json_encode($data);
}

// --- 2. LẤY DANH SÁCH NHÀ CUNG CẤP (CHO BẢNG QUẢN LÝ) ---
function handle_get_suppliers($conn) {
    $draw = intval($_POST['draw'] ?? 0);
    $start = intval($_POST['start'] ?? 0);
    $length = intval($_POST['length'] ?? 10);
    $searchTerm = $_POST['search_term'] ?? '';
    $debtStatus = $_POST['debt_status'] ?? '';

    $columns = [
        0 => 'supplier_code',
        1 => 'supplier_name',
        2 => 'supplier_phone',
        3 => 'tax_code',
        4 => 'last_import_date',
        5 => 'total_spent',
        6 => 'total_debt',
        7 => 'ID'
    ];

    $sql = "SELECT s.*, 
            (SELECT MAX(input_date) FROM cms_input WHERE supplier_id = s.ID AND deleted = 0) as last_import_date,
            COALESCE((SELECT SUM(total_money) FROM cms_input WHERE supplier_id = s.ID AND deleted = 0), 0) as total_spent,
            COALESCE((SELECT SUM(lack) FROM cms_input WHERE supplier_id = s.ID AND deleted = 0), 0) as total_debt
            FROM cms_suppliers s 
            WHERE 1=1";

    if (!empty($searchTerm)) {
        $sql .= " AND (s.supplier_name LIKE '%$searchTerm%' OR s.supplier_code LIKE '%$searchTerm%' OR s.supplier_phone LIKE '%$searchTerm%')";
    }

    $havingClause = "";
    if ($debtStatus == 'debt') {
        $havingClause = " HAVING total_debt > 0";
    } elseif ($debtStatus == 'no_debt') {
        $havingClause = " HAVING total_debt = 0";
    }
    
    $sql .= $havingClause;

    $countQuery = "SELECT COUNT(*) as count FROM ($sql) as filtered_table";
    $totalFiltered = $conn->query($countQuery)->fetch_assoc()['count'] ?? 0;

    if (isset($_POST['order'])) {
        $colIndex = $_POST['order'][0]['column'];
        $colName = $columns[$colIndex] ?? 'last_import_date';
        $colDir = $_POST['order'][0]['dir'] ?? 'DESC';
        $sql .= " ORDER BY $colName $colDir";
    } else {
        $sql .= " ORDER BY last_import_date DESC, ID DESC";
    }

    if ($length != -1) {
        $sql .= " LIMIT $start, $length";
    }

    $query = $conn->query($sql);
    $data = [];
    if ($query) {
        while ($row = $query->fetch_assoc()) {
            $data[] = $row;
        }
    }

    $sql_summary = "SELECT 
                        COUNT(*) as total_count,
                        SUM(CASE WHEN current_debt > 0 THEN 1 ELSE 0 END) as debt_count,
                        SUM(current_debt) as total_debt_amount
                    FROM (
                        SELECT s.ID, 
                        COALESCE((SELECT SUM(lack) FROM cms_input WHERE supplier_id = s.ID AND deleted = 0), 0) as current_debt
                        FROM cms_suppliers s
                    ) as subquery";
    $summary_res = $conn->query($sql_summary)->fetch_assoc();

    echo json_encode([
        "draw" => $draw,
        "recordsTotal" => intval($summary_res['total_count']),
        "recordsFiltered" => intval($totalFiltered),
        "data" => $data,
        "summary" => [
            "total_suppliers" => $summary_res['total_count'],
            "debt_suppliers" => $summary_res['debt_count'],
            "total_debt" => $summary_res['total_debt_amount']
        ]
    ]);
}

// ... CÁC HÀM XỬ LÝ KHÁC (ADD, EDIT, DELETE...) GIỮ NGUYÊN ...
function handle_add_edit_supplier($conn, $user_id, $action) {
    $supplier_id = intval($_POST['supplier_id'] ?? 0);
    $name = trim($_POST['supplier_name'] ?? '');
    $phone = trim($_POST['supplier_phone'] ?? '');
    $email = trim($_POST['supplier_email'] ?? '');
    $addr = trim($_POST['supplier_address'] ?? '');
    $tax = trim($_POST['tax_code'] ?? '');
    $note = trim($_POST['note'] ?? '');
    $code = trim($_POST['supplier_code'] ?? '');

    if (empty($name)) { echo json_encode(['status' => 'error', 'message' => 'Tên NCC là bắt buộc']); exit; }

    if ($action == 'add_supplier') {
        if (empty($code)) {
            $res = $conn->query("SELECT MAX(ID) FROM cms_suppliers");
            $last = $res->fetch_row()[0] ?? 0;
            $code = 'NCC' . str_pad($last + 1, 5, '0', STR_PAD_LEFT);
        }
        $stmt = $conn->prepare("INSERT INTO cms_suppliers (supplier_code, supplier_name, supplier_phone, supplier_email, supplier_addr, tax_code, notes, user_init, created) VALUES (?,?,?,?,?,?,?,?, NOW())");
        $stmt->bind_param("sssssssi", $code, $name, $phone, $email, $addr, $tax, $note, $user_id);
        $msg = 'Thêm thành công';
    } else {
        $stmt = $conn->prepare("UPDATE cms_suppliers SET supplier_name=?, supplier_code=?, supplier_phone=?, supplier_email=?, supplier_addr=?, tax_code=?, notes=? WHERE ID=?");
        $stmt->bind_param("sssssssi", $name, $code, $phone, $email, $addr, $tax, $note, $supplier_id);
        $msg = 'Cập nhật thành công';
    }
    if ($stmt->execute()) echo json_encode(['status' => 'success', 'message' => $msg]);
    else echo json_encode(['status' => 'error', 'message' => $stmt->error]);
}

function handle_get_supplier_details($conn) {
    $id = intval($_POST['id'] ?? 0);
    $stmt = $conn->prepare("SELECT * FROM cms_suppliers WHERE ID = ?");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $data = $stmt->get_result()->fetch_assoc();
    if ($data) echo json_encode(['status' => 'success', 'data' => $data]);
    else echo json_encode(['status' => 'error', 'message' => 'Không tìm thấy']);
}

function handle_delete_supplier($conn) {
    $id = intval($_POST['id'] ?? 0);
    $check = $conn->query("SELECT id FROM cms_input WHERE supplier_id = $id AND deleted = 0 LIMIT 1");
    if ($check->num_rows > 0) {
        echo json_encode(['status' => 'error', 'message' => 'NCC này đã có dữ liệu nhập hàng, không thể xóa!']);
    } else {
        $conn->query("DELETE FROM cms_suppliers WHERE ID = $id");
        echo json_encode(['status' => 'success', 'message' => 'Đã xóa']);
    }
}

function handle_pay_debt($conn) {
    $import_id = intval($_POST['import_id']);
    $amount = floatval($_POST['amount']);
    if ($amount <= 0) { echo json_encode(['status' => 'error', 'message' => 'Số tiền không hợp lệ']); exit; }

    $stmt = $conn->prepare("SELECT lack, payed FROM cms_input WHERE id = ?");
    $stmt->bind_param("i", $import_id);
    $stmt->execute();
    $slip = $stmt->get_result()->fetch_assoc();

    if (!$slip) { echo json_encode(['status' => 'error', 'message' => 'Phiếu nhập không tồn tại']); exit; }
    if ($amount > $slip['lack']) { echo json_encode(['status' => 'error', 'message' => 'Số tiền trả lớn hơn số nợ hiện tại']); exit; }

    $new_payed = $slip['payed'] + $amount;
    $new_lack = $slip['lack'] - $amount;
    $update = $conn->prepare("UPDATE cms_input SET payed = ?, lack = ? WHERE id = ?");
    $update->bind_param("ddi", $new_payed, $new_lack, $import_id);
    
    if ($update->execute()) echo json_encode(['status' => 'success', 'message' => 'Đã thanh toán thành công']);
    else echo json_encode(['status' => 'error', 'message' => 'Lỗi hệ thống']);
}

function handle_get_import_details($conn) {
    $id = intval($_POST['import_id']);
    $res = $conn->query("SELECT detail_input FROM cms_input WHERE id = $id");
    $row = $res->fetch_assoc();
    $details = json_decode($row['detail_input'], true);
    echo json_encode(['status' => 'success', 'data' => $details]);
}

// --- ROUTER (THÊM CASE SEARCH_SUPPLIERS) ---
switch ($action) {
    case 'search_suppliers': handle_search_suppliers($conn); break; // <-- ĐÂY LÀ DÒNG QUAN TRỌNG MỚI THÊM
    case 'get_suppliers': handle_get_suppliers($conn); break;
    case 'add_supplier':
    case 'edit_supplier': handle_add_edit_supplier($conn, $user_id, $action); break;
    case 'get_supplier_details': handle_get_supplier_details($conn); break;
    case 'delete_supplier': handle_delete_supplier($conn); break;
    case 'pay_debt': handle_pay_debt($conn); break;
    case 'get_import_details': handle_get_import_details($conn); break;
    default: echo json_encode(['status' => 'error', 'message' => 'Action invalid']); break;
}
$conn->close();
?>