<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../config/database.php';

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

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

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

switch ($action) {
    case 'get_products_list':
        handle_get_products_list($conn);
        break;
    case 'search_products_for_barcode':
        handle_search_products_for_barcode($conn);
        break;
    case 'get_product_details':
        handle_get_product_details($conn);
        break;
    case 'edit_product':
        handle_edit_product($conn);
        break;
    case 'delete_product':
        handle_delete_product($conn);
        break;
    case 'toggle_product_status':
        handle_toggle_product_status($conn);
        break;
    default:
        echo json_encode(['status' => 'error', 'message' => 'Hành động không hợp lệ.']);
        break;
}

function handle_toggle_product_status($conn) {
    $product_id = intval($_POST['product_id'] ?? 0);
    $current_status = intval($_POST['current_status'] ?? -1);

    if ($product_id <= 0 || !in_array($current_status, [0, 1])) {
        echo json_encode(['status' => 'error', 'message' => 'Dữ liệu không hợp lệ.']);
        return;
    }

    $new_status = $current_status == 1 ? 0 : 1;

    $stmt = $conn->prepare("UPDATE cms_products SET prd_status = ? WHERE ID = ?");
    $stmt->bind_param("ii", $new_status, $product_id);

    if ($stmt->execute()) {
        $message = $new_status == 0 ? 'Đã ngừng kinh doanh sản phẩm thành công!' : 'Đã khôi phục kinh doanh sản phẩm thành công!';
        echo json_encode(['status' => 'success', 'message' => $message]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Lỗi khi cập nhật trạng thái.']);
    }
    $stmt->close();
}

function handle_search_products_for_barcode($conn) {
    $term = $_GET['term'] ?? '';
    if (strlen($term) < 1) {
        echo json_encode([]);
        exit;
    }
    $searchTerm = "%" . $term . "%";
    
    $sql = "SELECT ID, prd_code, prd_name, prd_sell_price 
            FROM cms_products 
            WHERE (prd_name LIKE ? OR prd_code LIKE ?) 
            AND deleted = 0 AND prd_status = 1 
            LIMIT 15";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $searchTerm, $searchTerm);
    $stmt->execute();
    $result = $stmt->get_result();
    $products = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    $response_data = [];
    foreach($products as $p) {
        $response_data[] = ['id' => $p['ID'], 'code' => $p['prd_code'], 'name' => $p['prd_name'], 'price' => $p['prd_sell_price']];
    }
    
    echo json_encode($response_data);
}

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

    $baseQuery = "FROM cms_products p LEFT JOIN cms_products_group g ON p.prd_group_id = g.id LEFT JOIN cms_products_manufacture m ON p.prd_manufacture_id = m.id";
    $whereClauses = ["p.deleted = 0"];
    $params = [];
    $types = '';

    // Mặc định chỉ hiển thị sản phẩm đang kinh doanh (prd_status = 1)
    $whereClauses[] = "p.prd_status = ?";
    $params[] = 1;
    $types .= 'i';

    if (!empty($_POST['search_term'])) {
        $whereClauses[] = "(p.prd_name LIKE ? OR p.prd_code LIKE ?)";
        $searchTermWildcard = "%" . $_POST['search_term'] . "%";
        array_push($params, $searchTermWildcard, $searchTermWildcard);
        $types .= 'ss';
    }
    // Chỉ thêm điều kiện prd_status nếu được gửi từ client
    if (isset($_POST['prd_status']) && in_array($_POST['prd_status'], ['0', '1'])) { 
        $whereClauses = array_filter($whereClauses, function($clause) {
            return strpos($clause, 'p.prd_status =') === false;
        });
        $whereClauses[] = "p.prd_status = ?";
        $params = array_filter($params, function($param) {
            return $param !== 1;
        });
        $params[] = $_POST['prd_status'];
        $types = str_replace('i', '', $types) . 'i'; 
    }
    if (!empty($_POST['category_id'])) { 
        $whereClauses[] = "p.prd_group_id = ?"; 
        $params[] = $_POST['category_id']; 
        $types .= 'i'; 
    }
    if (!empty($_POST['manufacturer_id'])) { 
        $whereClauses[] = "p.prd_manufacture_id = ?"; 
        $params[] = $_POST['manufacturer_id']; 
        $types .= 'i'; 
    }

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

    $summaryQuery = "SELECT COUNT(p.ID) as total_products, 
                            COUNT(DISTINCT p.prd_manufacture_id) as total_manufacturers,
                            SUM(CASE WHEN p.prd_status = 1 THEN p.prd_sls * p.prd_origin_price ELSE 0 END) as total_inventory_value
                            $baseQuery $whereSql";
    $stmtSummary = $conn->prepare($summaryQuery);
    if (!empty($types)) { 
        $stmtSummary->bind_param($types, ...$params); 
    }
    $stmtSummary->execute();
    $summary_data = $stmtSummary->get_result()->fetch_assoc();
    $stmtSummary->close();

    $queryFiltered = "SELECT COUNT(p.ID) as total " . $baseQuery . $whereSql;
    $stmtFiltered = $conn->prepare($queryFiltered);
    if (!empty($types)) { 
        $stmtFiltered->bind_param($types, ...$params); 
    }
    $stmtFiltered->execute();
    $totalFiltered = $stmtFiltered->get_result()->fetch_assoc()['total'];
    $stmtFiltered->close();

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

    // Lấy thêm size, color, image để hiển thị
    $dataQuery = "SELECT p.ID as id, p.prd_name, p.prd_code, p.prd_image_url, p.prd_size, p.prd_color, p.prd_status, p.prd_sls AS prd_inventory, p.prd_sell_price, p.prd_sell_price2, g.prd_group_name, m.prd_manuf_name " . $baseQuery . $whereSql . " ORDER BY p.ID DESC LIMIT ?, ?";
    $dataTypes = $types . 'ii';
    $dataParams = array_merge($params, [$start, $length]);
    $stmt = $conn->prepare($dataQuery);
    $stmt->bind_param($dataTypes, ...$dataParams);
    $stmt->execute();
    $data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

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

function handle_get_product_details($conn) {
    $product_id = intval($_GET['product_id'] ?? 0);
    $response = ['status' => 'error', 'message' => 'ID sản phẩm không hợp lệ.'];
    if ($product_id > 0) {
        $stmt = $conn->prepare("SELECT * FROM cms_products WHERE ID = ?");
        $stmt->bind_param("i", $product_id);
        $stmt->execute();
        $data = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        if ($data) {
            $response = ['status' => 'success', 'data' => $data];
        } else {
            $response['message'] = 'Không tìm thấy sản phẩm.';
        }
    }
    echo json_encode($response);
}

function handle_edit_product($conn) {
    // --- CẬP NHẬT CHO POPUP SỬA NHANH ---
    $prd_id = intval($_POST['prd_id'] ?? 0);
    $prd_name = trim($_POST['prd_name'] ?? '');
    
    if (empty($prd_id) || empty($prd_name)) {
        echo json_encode(['status' => 'error', 'message' => 'Dữ liệu không hợp lệ.']);
        return;
    }

    // 1. Xử lý ảnh: Lấy ảnh cũ trước
    $old_data_query = $conn->query("SELECT prd_image_url FROM cms_products WHERE ID = $prd_id");
    $old_data = $old_data_query->fetch_assoc();
    $prd_image_url = $old_data['prd_image_url'] ?? '';

    // Nếu có upload ảnh mới
    if (isset($_FILES['prd_image']) && $_FILES['prd_image']['error'] == 0) {
        $target_dir = __DIR__ . '/../../img/products/';
        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0777, true);
        }
        
        $file_extension = strtolower(pathinfo($_FILES['prd_image']['name'], PATHINFO_EXTENSION));
        $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        
        if (in_array($file_extension, $allowed_extensions)) {
            $new_filename = 'prd_' . time() . '_' . rand(100, 999) . '.' . $file_extension;
            if (move_uploaded_file($_FILES['prd_image']['tmp_name'], $target_dir . $new_filename)) {
                $prd_image_url = 'img/products/' . $new_filename;
            }
        }
    }
    
    $prd_code = trim($_POST['prd_code'] ?? '');
    $prd_origin_price = floatval($_POST['prd_origin_price'] ?? 0);
    $prd_sell_price = floatval($_POST['prd_sell_price'] ?? 0);
    $prd_sell_price2 = floatval($_POST['prd_sell_price2'] ?? 0);
    $prd_group_id = intval($_POST['prd_group_id'] ?? 0);
    $prd_manufacture_id = intval($_POST['prd_manufacture_id'] ?? 0);
    $prd_unit_id = intval($_POST['prd_unit_id'] ?? 0);
    
    // Lấy Size và Màu dưới dạng STRING (Không dùng intval)
    $prd_size = trim($_POST['prd_size'] ?? ''); 
    $prd_color = trim($_POST['prd_color'] ?? '');

    $sql = "UPDATE cms_products SET 
                prd_name = ?, prd_code = ?, prd_origin_price = ?, 
                prd_sell_price = ?, prd_sell_price2 = ?, prd_group_id = ?, 
                prd_manufacture_id = ?, prd_unit_id = ?, 
                prd_size = ?, prd_color = ?, prd_image_url = ?, updated = NOW() 
            WHERE ID = ?";
            
    $stmt = $conn->prepare($sql);
    
    // ĐÃ SỬA LỖI Ở DÒNG NÀY: ssdddiiisssi (12 ký tự) tương ứng 12 biến
    $stmt->bind_param("ssdddiiisssi", 
        $prd_name, $prd_code, $prd_origin_price, $prd_sell_price, $prd_sell_price2, 
        $prd_group_id, $prd_manufacture_id, $prd_unit_id, 
        $prd_size, $prd_color, $prd_image_url, 
        $prd_id
    );
    
    if ($stmt->execute()) {
        $response = ['status' => 'success', 'message' => 'Cập nhật sản phẩm thành công!'];
    } else {
        $response = ['status' => 'error', 'message' => 'Lỗi khi cập nhật: ' . $stmt->error];
    }
    $stmt->close();
    echo json_encode($response);
}

function handle_delete_product($conn) {
    $product_id = intval($_POST['product_id'] ?? 0);
    if ($product_id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'ID sản phẩm không hợp lệ.']);
        return;
    }
    $stmt = $conn->prepare("UPDATE cms_products SET deleted = 1, prd_status = 0 WHERE ID = ?");
    $stmt->bind_param("i", $product_id);
    if ($stmt->execute()) {
        $response = ['status' => 'success', 'message' => 'Xóa sản phẩm thành công!'];
    } else {
        $response = ['status' => 'error', 'message' => 'Lỗi khi xóa sản phẩm.'];
    }
    $stmt->close();
    echo json_encode($response);
}