<?php
session_start();
require_once __DIR__ . '/../core/init.php';
use PhpOffice\PhpSpreadsheet\IOFactory;

$success_count = 0;
$error_count = 0;
$skipped_count = 0;
$errors = [];

if (isset($_FILES['import_file']) && $_FILES['import_file']['error'] == 0) {
    $fileName = $_FILES['import_file']['tmp_name'];
    try {
        $spreadsheet = IOFactory::load($fileName);
        $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
        
        $isFirstRow = true;
        foreach ($sheetData as $rowIndex => $row) {
            if ($isFirstRow) { $isFirstRow = false; continue; }

            $prd_name = trim($row['A'] ?? '');
            if (empty($prd_name)) continue; // Bỏ qua dòng trống

            $prd_code = trim($row['B'] ?? '');
            // Bỏ qua cột tồn kho, các cột khác giữ nguyên
            $prd_origin_price = (float)($row['C'] ?? 0);
            $prd_sell_price = (float)($row['D'] ?? 0);
            $prd_sell_price2 = (float)($row['E'] ?? 0);
            $category_name = trim($row['F'] ?? '');
            $manufacturer_name = trim($row['G'] ?? '');
            $unit_name = trim($row['H'] ?? '');
            $prd_tenquycach = trim($row['I'] ?? '');
            $prd_quycach = trim($row['J'] ?? '');
            
            // --- LOGIC MỚI: KIỂM TRA TRÙNG LẶP SẢN PHẨM ---
            $check_sql = "SELECT id FROM cms_products WHERE prd_name = ? OR (prd_code != '' AND prd_code = ?)";
            $stmt_check = $conn->prepare($check_sql);
            $stmt_check->bind_param("ss", $prd_name, $prd_code);
            $stmt_check->execute();
            $result_check = $stmt_check->get_result();
            if ($result_check->num_rows > 0) {
                // Nếu tìm thấy, bỏ qua và ghi nhận
                $skipped_count++;
                $stmt_check->close();
                continue;
            }
            $stmt_check->close();
            // --- KẾT THÚC LOGIC KIỂM TRA TRÙNG LẶP ---


            // --- Tìm ID từ Tên (logic giữ nguyên) ---
            $prd_group_id = 0;
            if(!empty($category_name)) {
                $stmt_group = $conn->prepare("SELECT id FROM cms_products_group WHERE prd_group_name = ?");
                $stmt_group->bind_param("s", $category_name); $stmt_group->execute(); $result_group = $stmt_group->get_result();
                if($result_group->num_rows > 0) $prd_group_id = $result_group->fetch_assoc()['id'];
            }

            $prd_manufacture_id = 0;
            if(!empty($manufacturer_name)) {
                $stmt_manuf = $conn->prepare("SELECT id FROM cms_products_manufacture WHERE prd_manuf_name = ?");
                $stmt_manuf->bind_param("s", $manufacturer_name); $stmt_manuf->execute(); $result_manuf = $stmt_manuf->get_result();
                if($result_manuf->num_rows > 0) $prd_manufacture_id = $result_manuf->fetch_assoc()['id'];
            }

            $prd_unit_id = 0;
             if(!empty($unit_name)) {
                $stmt_unit = $conn->prepare("SELECT id FROM cms_products_unit WHERE prd_unit_name = ?");
                $stmt_unit->bind_param("s", $unit_name); $stmt_unit->execute(); $result_unit = $stmt_unit->get_result();
                if($result_unit->num_rows > 0) $prd_unit_id = $result_unit->fetch_assoc()['id'];
            }
            
            // Câu lệnh INSERT đã bỏ qua cột tồn kho (prd_sls)
            $sql = "INSERT INTO cms_products (prd_name, prd_code, prd_origin_price, prd_sell_price, prd_sell_price2, prd_group_id, prd_manufacture_id, prd_unit_id, prd_tenquycach, prd_quycach, created, updated) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
            $stmt = $conn->prepare($sql);
            // Tham số bind tương ứng
            $stmt->bind_param("ssdddiiiss", $prd_name, $prd_code, $prd_origin_price, $prd_sell_price, $prd_sell_price2, $prd_group_id, $prd_manufacture_id, $prd_unit_id, $prd_tenquycach, $prd_quycach);
            
            if($stmt->execute()) {
                $success_count++;
            } else {
                $error_count++;
                $errors[] = "Dòng $rowIndex: " . $stmt->error;
            }
        }
        $message = "Import hoàn tất! <br>Thêm mới thành công: $success_count. <br>Bỏ qua (do trùng lặp): $skipped_count. <br>Thất bại: $error_count.";
        if($error_count > 0) $message .= "<br>Chi tiết lỗi: " . implode(", ", $errors);
        $_SESSION['import_message'] = $message;

    } catch (Exception $e) {
        $_SESSION['import_message'] = 'Lỗi khi đọc file Excel: ' . $e->getMessage();
    }
} else {
     $_SESSION['import_message'] = 'Không có file nào được upload hoặc có lỗi xảy ra.';
}

header('Location: /quanlybanhang/modules/products/list.php');
exit;
?>