<?php
//ini_set('display_errors', 1); // Bạn có thể xóa hoặc giữ lại dòng này để gỡ lỗi sau này
//error_reporting(E_ALL); // Bạn có thể xóa hoặc giữ lại dòng này để gỡ lỗi sau này

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

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

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

function handle_get_suppliers($conn) {
    $draw = intval($_POST['draw'] ?? 0);
    $start = intval($_POST['start'] ?? 0);
    $length = intval($_POST['length'] ?? 10);

    $summary = [];
    $summary['total_suppliers'] = $conn->query("SELECT COUNT(ID) FROM cms_suppliers")->fetch_row()[0] ?? 0;
    $debt_query = $conn->query("SELECT COUNT(DISTINCT supplier_id) as debt_suppliers, SUM(lack) as total_debt FROM cms_input WHERE lack > 0 AND deleted = 0")->fetch_assoc();
    $summary['debt_suppliers'] = $debt_query['debt_suppliers'] ?? 0;
    $summary['total_debt'] = $debt_query['total_debt'] ?? 0;

    $baseQuery = "FROM cms_suppliers s LEFT JOIN cms_input i ON s.ID = i.supplier_id AND i.deleted = 0";
    $whereClauses = [];
    $havingClauses = [];
    $params = [];
    $types = '';

    if (!empty($_POST['search_term'])) {
        $whereClauses[] = "(s.supplier_name LIKE ? OR s.supplier_code LIKE ? OR s.supplier_phone LIKE ?)";
        $searchTermWildcard = "%" . $_POST['search_term'] . "%";
        array_push($params, $searchTermWildcard, $searchTermWildcard, $searchTermWildcard);
        $types .= 'sss';
    }
    
    if (!empty($_POST['debt_status'])) {
        if ($_POST['debt_status'] === 'debt') {
            $havingClauses[] = "total_debt > 0";
        } elseif ($_POST['debt_status'] === 'no_debt') {
            $havingClauses[] = "(total_debt <= 0 OR total_debt IS NULL)";
        }
    }

    $groupBy = " GROUP BY s.ID ";
    $whereSql = !empty($whereClauses) ? " WHERE " . implode(" AND ", $whereClauses) : "";
    $havingSql = !empty($havingClauses) ? " HAVING " . implode(" AND ", $havingClauses) : "";
    
    $countQuery = "SELECT COUNT(*) as total FROM (SELECT s.ID, SUM(i.lack) as total_debt $baseQuery $whereSql $groupBy $havingSql) as subquery";
    $stmtFiltered = $conn->prepare($countQuery);
    if (!empty($types)) { $stmtFiltered->bind_param($types, ...$params); }
    $stmtFiltered->execute();
    $totalFiltered = $stmtFiltered->get_result()->fetch_assoc()['total'];
    $stmtFiltered->close();

    $dataQuery = "SELECT s.ID, s.supplier_code, s.supplier_name, s.supplier_phone, s.supplier_email, s.supplier_addr as supplier_address, s.tax_code, s.notes as note,
                    MAX(i.input_date) as last_import_date,
                    SUM(i.total_money) as total_spent,
                    SUM(i.lack) as total_debt
                  $baseQuery $whereSql $groupBy $havingSql
                  ORDER BY s.ID DESC LIMIT ?, ?";
                  
    $data_types = $types . 'ii';
    $data_params = array_merge($params, [$start, $length]);
    $stmt_data = $conn->prepare($dataQuery);
    if($stmt_data) {
        if(!empty($data_types)) $stmt_data->bind_param($data_types, ...$data_params);
        $stmt_data->execute();
        $data = $stmt_data->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt_data->close();
    } else {
        $data = [];
    }

    echo json_encode([
        "draw" => $draw,
        "recordsTotal" => intval($summary['total_suppliers']),
        "recordsFiltered" => intval($totalFiltered),
        "data" => $data,
        "summary" => $summary
    ]);
}

function handle_add_edit_supplier($conn, $user_id) {
    $supplier_id = intval($_POST['supplier_id'] ?? 0);
    $supplier_name = trim($_POST['supplier_name'] ?? '');
    if (empty($supplier_name)) { echo json_encode(['status' => 'error', 'message' => 'Tên nhà cung cấp là bắt buộc.']); exit(); }
    
    $supplier_code = trim($_POST['supplier_code'] ?? '');
    $supplier_phone = trim($_POST['supplier_phone'] ?? '');
    $supplier_email = trim($_POST['supplier_email'] ?? '');
    $supplier_address = trim($_POST['supplier_address'] ?? '');
    $tax_code = trim($_POST['tax_code'] ?? '');
    $note = trim($_POST['note'] ?? '');
    
    if ($supplier_id > 0) {
        $sql = "UPDATE cms_suppliers SET supplier_code=?, supplier_name=?, supplier_phone=?, supplier_email=?, supplier_addr=?, tax_code=?, notes=? WHERE ID=?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('sssssssi', $supplier_code, $supplier_name, $supplier_phone, $supplier_email, $supplier_address, $tax_code, $note, $supplier_id);
        $message = 'Cập nhật thông tin thành công!';
    } else {
        if (empty($supplier_code)) {
            $last_id_result = $conn->query("SELECT ID FROM cms_suppliers ORDER BY ID DESC LIMIT 1");
            $last_id = $last_id_result ? $last_id_result->fetch_row()[0] : 0;
            $supplier_code = 'NCC' . str_pad($last_id + 1, 5, '0', STR_PAD_LEFT);
        }
        $sql = "INSERT INTO cms_suppliers (supplier_code, supplier_name, supplier_phone, supplier_email, supplier_addr, tax_code, notes, user_init) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('sssssssi', $supplier_code, $supplier_name, $supplier_phone, $supplier_email, $supplier_address, $tax_code, $note, $user_id);
        $message = 'Thêm nhà cung cấp thành công!';
    }
    
    if ($stmt && $stmt->execute()) {
        $response = ['status' => 'success', 'message' => $message];
    } else {
        $response = ['status' => 'error', 'message' => 'Lỗi khi lưu: ' . ($stmt ? $stmt->error : $conn->error)];
    }
    if($stmt) $stmt->close();
    echo json_encode($response);
}

function handle_get_supplier_details($conn) {
    $id = intval($_POST['id'] ?? 0);
    if ($id <= 0) { echo json_encode(['status' => 'error', 'message' => 'ID nhà cung cấp không hợp lệ.']); exit(); }
    
    $stmt = $conn->prepare("SELECT ID, supplier_code, supplier_name, supplier_phone, supplier_email, supplier_addr as supplier_address, tax_code, notes as note FROM cms_suppliers WHERE ID = ?");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($supplier = $result->fetch_assoc()) {
        echo json_encode(['status' => 'success', 'data' => $supplier]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Không tìm thấy nhà cung cấp.']);
    }
    $stmt->close();
}

function handle_delete_supplier($conn) {
    $id = intval($_POST['id'] ?? 0);
    if ($id <= 0) { echo json_encode(['status' => 'error', 'message' => 'ID nhà cung cấp không hợp lệ.']); exit(); }
    
    $stmt = $conn->prepare("DELETE FROM cms_suppliers WHERE ID = ?");
    $stmt->bind_param('i', $id);
    if ($stmt->execute()) {
        echo json_encode(['status' => 'success', 'message' => 'Đã xóa nhà cung cấp.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Lỗi khi xóa: ' . $stmt->error]);
    }
    $stmt->close();
}

switch ($action) {
    case 'get_suppliers':
        handle_get_suppliers($conn);
        break;
    case 'add_supplier':
    case 'edit_supplier':
        handle_add_edit_supplier($conn, $user_id);
        break;
    case 'get_supplier_details':
        handle_get_supplier_details($conn);
        break;
    case 'delete_supplier':
        handle_delete_supplier($conn);
        break;
    default:
        echo json_encode(['status' => 'error', 'message' => 'Hành động không hợp lệ.']);
        break;
}

$conn->close();
?>