<?php
session_start();
require_once 'includes/config.php';

if (!isset($_SESSION['vai_tro']) || ($_SESSION['vai_tro'] !== 'to_chuc' && $_SESSION['vai_tro'] !== 'admin')) {
    die("Khu vực quản lý kho bãi nội bộ. Vui lòng đăng nhập với tài khoản cơ sở hoặc admin.");
}

$is_admin = ($_SESSION['vai_tro'] === 'admin');
$id_kho_hien_tai = isset($_SESSION['id']) ? (int)$_SESSION['id'] : 0;
$active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'san-pham';
$search_san_pham = trim($_GET['search_san_pham'] ?? '');
$filter_danh_muc = trim($_GET['filter_danh_muc'] ?? '');
$filter_trang_thai = trim($_GET['filter_trang_thai'] ?? '');
$search_kho = trim($_GET['search_kho'] ?? '');
$prefill_product = isset($_GET['prefill_product']) ? (int)$_GET['prefill_product'] : 0;
$prefill_action = trim($_GET['prefill_action'] ?? 'nhap');
$edit_category_id = isset($_GET['edit_category_id']) ? (int)$_GET['edit_category_id'] : 0;
$thong_bao = '';
$loi = '';
$history_table_ready = true;
$summary_products = 0;
$summary_stock = 0;
$summary_pending = 0;
$summary_value = 0;
$danh_sach_danh_muc = [];
$danh_sach_san_pham = [];
$san_pham_sua = null;
$danh_muc_sua = null;
$ton_kho_co_so = [];
$lich_su_kho = [];
$san_pham_sap_het = [];
$don_hang_cho = [];

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS danh_muc_san_pham (
        id INT AUTO_INCREMENT PRIMARY KEY,
        ten_danh_muc VARCHAR(100) NOT NULL UNIQUE,
        slug VARCHAR(100) NOT NULL UNIQUE,
        mo_ta VARCHAR(255) DEFAULT NULL,
        trang_thai VARCHAR(20) NOT NULL DEFAULT 'hien_thi',
        ngay_tao TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS lich_su_kho (
        id INT AUTO_INCREMENT PRIMARY KEY,
        id_to_chuc INT NOT NULL,
        id_san_pham INT NOT NULL,
        loai_thao_tac VARCHAR(20) NOT NULL,
        so_luong INT NOT NULL DEFAULT 0,
        vi_tri_kho VARCHAR(255) DEFAULT NULL,
        id_don_hang INT DEFAULT NULL,
        ghi_chu VARCHAR(255) DEFAULT NULL,
        ngay_tao TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        KEY idx_lich_su_kho_to_chuc (id_to_chuc),
        KEY idx_lich_su_kho_san_pham (id_san_pham),
        KEY idx_lich_su_kho_ngay (ngay_tao)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Exception $e) {
    $history_table_ready = false;
    error_log('Unable to create lich_su_kho: ' . $e->getMessage());
}

try {
    $pdo->prepare("INSERT IGNORE INTO danh_muc_san_pham (ten_danh_muc, slug) VALUES (?, ?)")->execute(['Nhạc cụ', 'nhac_cu']);
    $pdo->prepare("INSERT IGNORE INTO danh_muc_san_pham (ten_danh_muc, slug) VALUES (?, ?)")->execute(['Tranh vẽ & họa cụ', 'tranh_ve']);
    $pdo->prepare("INSERT IGNORE INTO danh_muc_san_pham (ten_danh_muc, slug) VALUES (?, ?)")->execute(['Thiết bị âm thanh', 'thiet_bi']);
    $pdo->prepare("INSERT IGNORE INTO danh_muc_san_pham (ten_danh_muc, slug) VALUES (?, ?)")->execute(['Trang phục biểu diễn', 'trang_phuc']);
} catch (Exception $e) {
    error_log('Unable to seed categories: ' . $e->getMessage());
}

// Ensure product flags exist (moi, noi_bat, ban_chay)
try {
    $col = $pdo->prepare("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'san_pham_gian_hang' AND COLUMN_NAME = 'moi'");
    $col->execute();
    if (!$col->fetch()) {
        $pdo->exec("ALTER TABLE san_pham_gian_hang ADD COLUMN moi TINYINT(1) NOT NULL DEFAULT 0");
    }
    $col = $pdo->prepare("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'san_pham_gian_hang' AND COLUMN_NAME = 'noi_bat'");
    $col->execute();
    if (!$col->fetch()) {
        $pdo->exec("ALTER TABLE san_pham_gian_hang ADD COLUMN noi_bat TINYINT(1) NOT NULL DEFAULT 0");
    }
    $col = $pdo->prepare("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'san_pham_gian_hang' AND COLUMN_NAME = 'ban_chay'");
    $col->execute();
    if (!$col->fetch()) {
        $pdo->exec("ALTER TABLE san_pham_gian_hang ADD COLUMN ban_chay TINYINT(1) NOT NULL DEFAULT 0");
    }
} catch (Exception $e) {
    error_log('Unable to add product flag columns: ' . $e->getMessage());
}

if (isset($_GET['edit_id'])) {
    $edit_id = (int)$_GET['edit_id'];
} else {
    $edit_id = 0;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['luu_danh_muc'])) {
        $category_id = (int)($_POST['id_danh_muc'] ?? 0);
        $ten_danh_muc = trim($_POST['ten_danh_muc'] ?? '');
        $slug = trim($_POST['slug'] ?? '');
        if ($slug === '') {
            $slug = strtolower(str_replace(' ', '_', $ten_danh_muc));
            $slug = preg_replace('/[^a-z0-9_]+/', '_', $slug);
            $slug = trim($slug, '_');
        }
        if ($ten_danh_muc === '') {
            $loi = 'Vui lòng nhập tên danh mục.';
        } else {
            try {
                if ($category_id > 0) {
                    $pdo->prepare("UPDATE danh_muc_san_pham SET ten_danh_muc = ?, slug = ? WHERE id = ?")
                        ->execute([$ten_danh_muc, $slug, $category_id]);
                    $thong_bao = 'Đã cập nhật danh mục.';
                } else {
                    $pdo->prepare("INSERT INTO danh_muc_san_pham (ten_danh_muc, slug) VALUES (?, ?)")
                        ->execute([$ten_danh_muc, $slug]);
                    $thong_bao = 'Đã thêm danh mục mới.';
                }
            } catch (Exception $e) {
                $loi = 'Lỗi lưu danh mục: ' . $e->getMessage();
            }
        }
    }

    if (isset($_POST['xoa_danh_muc'])) {
        $category_id = (int)($_POST['id_danh_muc'] ?? 0);
        if ($category_id > 0) {
            try {
                $pdo->prepare("DELETE FROM danh_muc_san_pham WHERE id = ?")->execute([$category_id]);
                $thong_bao = 'Đã xóa danh mục.';
            } catch (Exception $e) {
                $loi = 'Lỗi xóa danh mục: ' . $e->getMessage();
            }
        }
    }

    if (isset($_POST['luu_san_pham'])) {
        $id_san_pham = isset($_POST['id_san_pham']) ? (int)$_POST['id_san_pham'] : 0;
        $ma_hieu = trim($_POST['ma_hieu'] ?? '');
        $ten_san_pham = trim($_POST['ten_san_pham'] ?? '');
        $danh_muc = trim($_POST['danh_muc'] ?? '');
        $mo_ta = trim($_POST['mo_ta'] ?? '');
        $hinh_anh = trim($_POST['hinh_anh'] ?? '');
        if (!empty($_FILES['hinh_anh_file']['name']) && is_uploaded_file($_FILES['hinh_anh_file']['tmp_name'])) {
            $thu_muc_upload = __DIR__ . '/uploads/san-pham/';
            if (!is_dir($thu_muc_upload)) {
                mkdir($thu_muc_upload, 0755, true);
            }
            $ten_file = time() . '_' . preg_replace('/[^A-Za-z0-9._-]/', '_', basename($_FILES['hinh_anh_file']['name']));
            $duong_dan = $thu_muc_upload . $ten_file;
            if (move_uploaded_file($_FILES['hinh_anh_file']['tmp_name'], $duong_dan)) {
                $hinh_anh = 'uploads/san-pham/' . $ten_file;
            } else {
                $loi = 'Không thể tải ảnh lên. Vui lòng thử lại.';
            }
        }
        $gia_goc = (int)($_POST['gia_goc'] ?? 0);
        $gia_ban = 0;
        $gia_khuyen_mai = 0;
        $ty_le_hoa_hong = 0;
        $so_luong_ton = (int)($_POST['so_luong_ton'] ?? 0);
        $vi_tri_kho = trim($_POST['vi_tri_kho'] ?? '');
        $trang_thai = trim($_POST['trang_thai'] ?? 'hien_thi');

        if ($ten_san_pham === '' || $gia_goc <= 0) {
            $loi = "Vui lòng nhập tên sản phẩm và giá gốc hợp lệ.";
        } else {
            try {
                $moi_flag = isset($_POST['moi']) ? 1 : 0;
                $noi_bat_flag = isset($_POST['noi_bat']) ? 1 : 0;
                $ban_chay_flag = isset($_POST['ban_chay']) ? 1 : 0;

                if ($id_san_pham > 0) {
                    $stmt = $pdo->prepare("UPDATE san_pham_gian_hang SET ma_hieu = ?, ten_san_pham = ?, danh_muc = ?, mo_ta = ?, hinh_anh = ?, gia_goc = ?, trang_thai = ?, moi = ?, noi_bat = ?, ban_chay = ? WHERE id = ?");
                    $stmt->execute([$ma_hieu, $ten_san_pham, $danh_muc, $mo_ta, $hinh_anh, $gia_goc, $trang_thai, $moi_flag, $noi_bat_flag, $ban_chay_flag, $id_san_pham]);
                    $product_id = $id_san_pham;
                    $thong_bao = "Đã cập nhật sản phẩm thành công.";
                } else {
                    $stmt = $pdo->prepare("INSERT INTO san_pham_gian_hang (ma_hieu, ten_san_pham, danh_muc, mo_ta, hinh_anh, gia_goc, gia_ban, gia_khuyen_mai, ty_le_hoa_hong, so_luong_ton, trang_thai, moi, noi_bat, ban_chay) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$ma_hieu, $ten_san_pham, $danh_muc, $mo_ta, $hinh_anh, $gia_goc, 0, 0, 0, $so_luong_ton, $trang_thai, $moi_flag, $noi_bat_flag, $ban_chay_flag]);
                    $product_id = (int)$pdo->lastInsertId();
                    $thong_bao = "Đã thêm sản phẩm mới vào kho.";
                }

                if ($id_san_pham <= 0 && $product_id > 0 && $so_luong_ton > 0) {
                    $stmt_stock = $pdo->prepare("SELECT id, so_luong_ton FROM quan_ly_kho_hang WHERE id_to_chuc = ? AND id_san_pham = ?");
                    $stmt_stock->execute([$id_kho_hien_tai, $product_id]);
                    $stock_row = $stmt_stock->fetch(PDO::FETCH_ASSOC);
                    if ($stock_row) {
                        $pdo->prepare("UPDATE quan_ly_kho_hang SET so_luong_ton = so_luong_ton + ?, vi_tri_kho = COALESCE(NULLIF(?, ''), vi_tri_kho) WHERE id = ?")
                            ->execute([$so_luong_ton, $vi_tri_kho ?? '', $stock_row['id']]);
                    } else {
                        $pdo->prepare("INSERT INTO quan_ly_kho_hang (id_to_chuc, id_san_pham, so_luong_ton, vi_tri_kho) VALUES (?, ?, ?, ?)")
                            ->execute([$id_kho_hien_tai, $product_id, $so_luong_ton, $vi_tri_kho ?? '']);
                    }
                }
            } catch (PDOException $e) {
                $loi = "Lỗi lưu sản phẩm: " . $e->getMessage();
            }
        }
    }

    if (isset($_POST['xoa_san_pham'])) {
        $id_san_pham = (int)($_POST['id_san_pham'] ?? 0);
        if ($id_san_pham > 0) {
            try {
                $pdo->beginTransaction();
                $pdo->prepare("DELETE FROM quan_ly_kho_hang WHERE id_san_pham = ?")->execute([$id_san_pham]);
                $pdo->prepare("DELETE FROM chinh_sach_kinh_doanh WHERE id_san_pham = ?")->execute([$id_san_pham]);
                $pdo->prepare("DELETE FROM san_pham_gian_hang WHERE id = ?")->execute([$id_san_pham]);
                $pdo->commit();
                $thong_bao = "Đã xóa sản phẩm khỏi hệ thống.";
            } catch (Exception $e) {
                $pdo->rollBack();
                $loi = "Lỗi xóa sản phẩm: " . $e->getMessage();
            }
        }
    }

    if (isset($_POST['cap_nhat_ton_kho'])) {
        $id_san_pham = (int)($_POST['id_san_pham'] ?? 0);
        $so_luong = (int)($_POST['so_luong'] ?? 0);
        $vi_tri_kho = trim($_POST['vi_tri_kho'] ?? '');
        $loai_thao_tac = trim($_POST['loai_thao_tac'] ?? 'nhap');

        if ($id_san_pham <= 0 || $so_luong <= 0) {
            $loi = "Vui lòng chọn sản phẩm và nhập số lượng hợp lệ.";
        } else {
            try {
                $pdo->beginTransaction();
                $stmt_check = $pdo->prepare("SELECT id, so_luong_ton FROM quan_ly_kho_hang WHERE id_to_chuc = ? AND id_san_pham = ?");
                $stmt_check->execute([$id_kho_hien_tai, $id_san_pham]);
                $hang_kho = $stmt_check->fetch(PDO::FETCH_ASSOC);

                if ($loai_thao_tac === 'xuat') {
                    $ton_hien_tai = (int)($hang_kho['so_luong_ton'] ?? 0);
                    if ($ton_hien_tai < $so_luong) {
                        throw new Exception("Tồn kho hiện tại không đủ để xuất $so_luong sản phẩm.");
                    }
                    if ($hang_kho) {
                        $pdo->prepare("UPDATE quan_ly_kho_hang SET so_luong_ton = so_luong_ton - ?, vi_tri_kho = ? WHERE id = ?")->execute([$so_luong, $vi_tri_kho, $hang_kho['id']]);
                    }
                } else {
                    if ($hang_kho) {
                        $pdo->prepare("UPDATE quan_ly_kho_hang SET so_luong_ton = so_luong_ton + ?, vi_tri_kho = ? WHERE id = ?")->execute([$so_luong, $vi_tri_kho, $hang_kho['id']]);
                    } else {
                        $pdo->prepare("INSERT INTO quan_ly_kho_hang (id_to_chuc, id_san_pham, so_luong_ton, vi_tri_kho) VALUES (?, ?, ?, ?)")->execute([$id_kho_hien_tai, $id_san_pham, $so_luong, $vi_tri_kho]);
                    }
                }

                if ($history_table_ready) {
                    $pdo->prepare("INSERT INTO lich_su_kho (id_to_chuc, id_san_pham, loai_thao_tac, so_luong, vi_tri_kho, ghi_chu) VALUES (?, ?, ?, ?, ?, ?)")
                        ->execute([$id_kho_hien_tai, $id_san_pham, $loai_thao_tac, $so_luong, $vi_tri_kho, $loai_thao_tac === 'xuat' ? 'Xuất kho thủ công' : 'Nhập kho thủ công']);
                }

                $pdo->commit();
                $thong_bao = $loai_thao_tac === 'xuat' ? "Đã xuất kho thành công." : "Đã nhập kho thành công.";
            } catch (Exception $e) {
                $pdo->rollBack();
                $loi = "Lỗi cập nhật kho: " . $e->getMessage();
            }
        }
    }

    if (isset($_POST['xac_nhan_giao_hang'])) {
        $id_don_hang = (int)($_POST['id_don_hang'] ?? 0);
        try {
            $pdo->beginTransaction();
            $stmt_don = $pdo->prepare("SELECT * FROM don_hang_gian_hang WHERE id = ? AND id_kho_xuat = ? AND trang_thai = 'dang_giao' FOR UPDATE");
            $stmt_don->execute([$id_don_hang, $id_kho_hien_tai]);
            $don_hang = $stmt_don->fetch(PDO::FETCH_ASSOC);
            if (!$don_hang) {
                throw new Exception("Đơn hàng không tồn tại hoặc đã được xử lý.");
            }

            $stmt_cs = $pdo->prepare("SELECT * FROM chinh_sach_kinh_doanh WHERE id_san_pham = ?");
            $stmt_cs->execute([$don_hang['id_san_pham']]);
            $chinh_sach = $stmt_cs->fetch(PDO::FETCH_ASSOC);
            if (!$chinh_sach) {
                throw new Exception("Sản phẩm chưa có chính sách phân bổ doanh thu.");
            }

            $tong_tien = (int)($don_hang['tong_tien'] ?? 0);
            $tien_kho_bai = $tong_tien * ($chinh_sach['ty_le_kho_bai'] / 100);
            $tien_affiliate = $tong_tien * ($chinh_sach['ty_le_affiliate'] / 100);

            if ($tien_kho_bai > 0) {
                $pdo->prepare("INSERT INTO giao_dich_tai_chinh (id_nguoi_nhan, so_tien, loai_giao_dich, trang_thai) VALUES (?, ?, 'doanh_thu_kho', 'da_chuyen')")->execute([$id_kho_hien_tai, $tien_kho_bai]);
            }

            if (!empty($don_hang['ma_gioi_thieu'])) {
                $stmt_nguoi_gt = $pdo->prepare("SELECT id FROM thanh_vien WHERE ma_gioi_thieu = ? AND vai_tro = 'ca_nhan'");
                $stmt_nguoi_gt->execute([$don_hang['ma_gioi_thieu']]);
                $nguoi_gioi_thieu = $stmt_nguoi_gt->fetch();
                if ($nguoi_gioi_thieu && $tien_affiliate > 0) {
                    $pdo->prepare("INSERT INTO giao_dich_tai_chinh (id_nguoi_nhan, so_tien, loai_giao_dich, trang_thai) VALUES (?, ?, 'hoa_hong_gioi_thieu', 'da_chuyen')")->execute([$nguoi_gioi_thieu['id'], $tien_affiliate]);
                }
            }

            $so_luong_dat = max(1, (int)($don_hang['so_luong'] ?? 1));
            $stmt_stock_row = $pdo->prepare("SELECT id, so_luong_ton FROM quan_ly_kho_hang WHERE id_to_chuc = ? AND id_san_pham = ? FOR UPDATE");
            $stmt_stock_row->execute([$id_kho_hien_tai, $don_hang['id_san_pham']]);
            $stock_row = $stmt_stock_row->fetch(PDO::FETCH_ASSOC);
            if (!$stock_row || (int)($stock_row['so_luong_ton'] ?? 0) < $so_luong_dat) {
                throw new Exception("Tồn kho hiện tại không đủ để giao đơn hàng này.");
            }

            $stmt_tru_kho = $pdo->prepare("UPDATE quan_ly_kho_hang SET so_luong_ton = so_luong_ton - ? WHERE id = ? AND so_luong_ton >= ?");
            $stmt_tru_kho->execute([$so_luong_dat, $stock_row['id'], $so_luong_dat]);
            if ($stmt_tru_kho->rowCount() !== 1) {
                throw new Exception("Không thể trừ kho cho đơn hàng này.");
            }

            if ($history_table_ready) {
                $pdo->prepare("INSERT INTO lich_su_kho (id_to_chuc, id_san_pham, loai_thao_tac, so_luong, id_don_hang, ghi_chu) VALUES (?, ?, 'xuat', ?, ?, ?)")->execute([$id_kho_hien_tai, $don_hang['id_san_pham'], $so_luong_dat, $id_don_hang, 'Xuất kho theo đơn hàng']);
            }
            $pdo->prepare("UPDATE don_hang_gian_hang SET trang_thai = 'hoan_thanh' WHERE id = ?")->execute([$id_don_hang]);
            $pdo->commit();
            $thong_bao = "Đã xác nhận giao hàng và phân bổ doanh thu.";
        } catch (Exception $e) {
            $pdo->rollBack();
            $loi = "Lỗi xác nhận giao hàng: " . $e->getMessage();
        }
    }
}

try {
    $stmt_summary = $pdo->query("SELECT COUNT(*) AS total_san_pham FROM san_pham_gian_hang WHERE trang_thai != 'an'");
    $summary_products = (int)$stmt_summary->fetchColumn();

    $stmt_stock_summary = $pdo->query("SELECT COALESCE(SUM(ql.so_luong_ton),0) AS total_ton, COALESCE(SUM(ql.so_luong_ton * sp.gia_goc),0) AS gia_tri_ton FROM quan_ly_kho_hang ql JOIN san_pham_gian_hang sp ON sp.id = ql.id_san_pham");
    $stock_summary = $stmt_stock_summary->fetch(PDO::FETCH_ASSOC);
    $summary_stock = (int)($stock_summary['total_ton'] ?? 0);
    $summary_value = (int)($stock_summary['gia_tri_ton'] ?? 0);

    $stmt_pending_summary = $pdo->query("SELECT COUNT(*) AS total_don FROM don_hang_gian_hang WHERE trang_thai = 'dang_giao'");
    $summary_pending = (int)$stmt_pending_summary->fetchColumn();

    $sql_san_pham = "SELECT sp.*, COALESCE(ql.so_luong_ton, 0) AS ton_kho_hien_tai FROM san_pham_gian_hang sp LEFT JOIN danh_muc_san_pham dm ON dm.slug COLLATE utf8mb4_unicode_ci = sp.danh_muc COLLATE utf8mb4_unicode_ci OR dm.ten_danh_muc COLLATE utf8mb4_unicode_ci = sp.danh_muc COLLATE utf8mb4_unicode_ci LEFT JOIN quan_ly_kho_hang ql ON ql.id_san_pham = sp.id AND ql.id_to_chuc = $id_kho_hien_tai WHERE 1=1";
    $params_san_pham = [];
    if ($search_san_pham !== '') {
        $like = '%' . $search_san_pham . '%';
        $sql_san_pham .= " AND (sp.ten_san_pham LIKE ? OR sp.ma_hieu LIKE ? OR sp.mo_ta LIKE ?)";
        $params_san_pham[] = $like;
        $params_san_pham[] = $like;
        $params_san_pham[] = $like;
    }
    if ($filter_danh_muc !== '') {
        $sql_san_pham .= " AND (sp.danh_muc COLLATE utf8mb4_unicode_ci = ? COLLATE utf8mb4_unicode_ci OR dm.slug COLLATE utf8mb4_unicode_ci = ? COLLATE utf8mb4_unicode_ci OR dm.ten_danh_muc COLLATE utf8mb4_unicode_ci = ? COLLATE utf8mb4_unicode_ci)";
        $params_san_pham[] = $filter_danh_muc;
        $params_san_pham[] = $filter_danh_muc;
        $params_san_pham[] = $filter_danh_muc;
    }
    if ($filter_trang_thai !== '') {
        $sql_san_pham .= " AND sp.trang_thai = ?";
        $params_san_pham[] = $filter_trang_thai;
    }
    $sql_san_pham .= " ORDER BY sp.ten_san_pham ASC";
    $stmt_san_pham = $pdo->prepare($sql_san_pham);
    $stmt_san_pham->execute($params_san_pham);
    $danh_sach_san_pham = $stmt_san_pham->fetchAll(PDO::FETCH_ASSOC);

    $stmt_categories = $pdo->query("SELECT * FROM danh_muc_san_pham ORDER BY ten_danh_muc ASC");
    $danh_sach_danh_muc = $stmt_categories->fetchAll(PDO::FETCH_ASSOC);
    $category_lookup = [];
    foreach ($danh_sach_danh_muc as $dm) {
        $category_lookup[$dm['slug']] = $dm['ten_danh_muc'];
    }

    if ($edit_category_id > 0) {
        $stmt_edit_category = $pdo->prepare("SELECT * FROM danh_muc_san_pham WHERE id = ? LIMIT 1");
        $stmt_edit_category->execute([$edit_category_id]);
        $danh_muc_sua = $stmt_edit_category->fetch(PDO::FETCH_ASSOC);
    } else {
        $danh_muc_sua = null;
    }

    if ($edit_id > 0) {
        $stmt_edit = $pdo->prepare("SELECT * FROM san_pham_gian_hang WHERE id = ? LIMIT 1");
        $stmt_edit->execute([$edit_id]);
        $san_pham_sua = $stmt_edit->fetch(PDO::FETCH_ASSOC);
    } else {
        $san_pham_sua = null;
    }

    $sql_kho = "SELECT ql.*, sp.ten_san_pham, sp.ma_hieu, sp.danh_muc, sp.gia_goc, sp.mo_ta FROM quan_ly_kho_hang ql JOIN san_pham_gian_hang sp ON ql.id_san_pham = sp.id WHERE ql.id_to_chuc = ?";
    $params_kho = [$id_kho_hien_tai];
    if ($search_kho !== '') {
        $like = '%' . $search_kho . '%';
        $sql_kho .= " AND (sp.ten_san_pham LIKE ? OR sp.ma_hieu LIKE ?)";
        $params_kho[] = $like;
        $params_kho[] = $like;
    }
    $sql_kho .= " ORDER BY sp.ten_san_pham ASC";
    $stmt_kho = $pdo->prepare($sql_kho);
    $stmt_kho->execute($params_kho);
    $ton_kho_co_so = $stmt_kho->fetchAll(PDO::FETCH_ASSOC);

    if ($history_table_ready) {
        $stmt_lich_su = $pdo->prepare("SELECT lsk.*, sp.ten_san_pham, sp.ma_hieu FROM lich_su_kho lsk JOIN san_pham_gian_hang sp ON lsk.id_san_pham = sp.id WHERE lsk.id_to_chuc = ? ORDER BY lsk.ngay_tao DESC LIMIT 20");
        $stmt_lich_su->execute([$id_kho_hien_tai]);
        $lich_su_kho = $stmt_lich_su->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $lich_su_kho = [];
    }

    $stmt_low_stock = $pdo->prepare("SELECT ql.id_san_pham, ql.so_luong_ton, sp.ten_san_pham, sp.ma_hieu FROM quan_ly_kho_hang ql JOIN san_pham_gian_hang sp ON sp.id = ql.id_san_pham WHERE ql.id_to_chuc = ? AND ql.so_luong_ton <= 5 ORDER BY ql.so_luong_ton ASC, sp.ten_san_pham ASC LIMIT 10");
    $stmt_low_stock->execute([$id_kho_hien_tai]);
    $san_pham_sap_het = $stmt_low_stock->fetchAll(PDO::FETCH_ASSOC);

    $stmt_danh_sach = $pdo->prepare("SELECT dh.*, sp.ten_san_pham, sp.hinh_anh FROM don_hang_gian_hang dh JOIN san_pham_gian_hang sp ON dh.id_san_pham = sp.id WHERE dh.id_kho_xuat = ? AND dh.trang_thai = 'dang_giao' ORDER BY dh.ngay_dat DESC");
    $stmt_danh_sach->execute([$id_kho_hien_tai]);
    $don_hang_cho = $stmt_danh_sach->fetchAll(PDO::FETCH_ASSOC);

    // === Dữ liệu tab lợi nhuận ===
    $vat_rate = 0.10; // VAT 10%
    $loc_thang = isset($_GET['loc_thang']) ? trim($_GET['loc_thang']) : date('Y-m');

    // Tổng hợp theo từng sản phẩm
    $stmt_ln = $pdo->prepare("
        SELECT
            sp.id, sp.ten_san_pham, sp.ma_hieu, sp.gia_goc,
            cs.ty_le_affiliate, cs.ty_le_kho_bai, cs.phi_nen_tang,
            COUNT(dh.id) AS so_don,
            COUNT(dh.id) AS tong_so_luong,
            SUM(dh.tong_tien) AS tong_doanh_thu_vat
        FROM don_hang_gian_hang dh
        JOIN san_pham_gian_hang sp ON sp.id = dh.id_san_pham
        LEFT JOIN chinh_sach_kinh_doanh cs ON cs.id_san_pham = sp.id
        WHERE dh.id_kho_xuat = ?
          AND dh.trang_thai = 'hoan_thanh'
          AND DATE_FORMAT(dh.ngay_dat, '%Y-%m') = ?
        GROUP BY sp.id, sp.ten_san_pham, sp.ma_hieu, sp.gia_goc,
                 cs.ty_le_affiliate, cs.ty_le_kho_bai, cs.phi_nen_tang
        ORDER BY tong_doanh_thu_vat DESC
    ");
    $stmt_ln->execute([$id_kho_hien_tai, $loc_thang]);
    $bao_cao_loi_nhuan = $stmt_ln->fetchAll(PDO::FETCH_ASSOC);

    // Tính toán từng dòng và tổng cộng
    $tong_cong = ['doanh_thu_vat'=>0,'vat'=>0,'doanh_thu_chua_vat'=>0,'gia_von'=>0,'hoa_hong'=>0,'phi_nen_tang'=>0,'loi_nhuan'=>0];
    foreach ($bao_cao_loi_nhuan as &$row) {
        $sl          = (int)($row['tong_so_luong'] ?? 1);
        $dt_vat      = (float)$row['tong_doanh_thu_vat'];
        $dt_chua_vat = round($dt_vat / (1 + $vat_rate));
        $vat         = $dt_vat - $dt_chua_vat;
        $gia_von     = (float)$row['gia_goc'] * $sl;
        $hoa_hong    = round($dt_chua_vat * ((float)($row['ty_le_affiliate'] ?? 0) / 100));
        $phi_nen_tang = (float)($row['phi_nen_tang'] ?? 0) * $sl;
        $loi_nhuan   = $dt_chua_vat - $gia_von - $hoa_hong - $phi_nen_tang;

        $row['dt_vat']       = $dt_vat;
        $row['dt_chua_vat']  = $dt_chua_vat;
        $row['vat']          = $vat;
        $row['gia_von']      = $gia_von;
        $row['hoa_hong']     = $hoa_hong;
        $row['phi_nen_tang_tong'] = $phi_nen_tang;
        $row['loi_nhuan']    = $loi_nhuan;

        $tong_cong['doanh_thu_vat']    += $dt_vat;
        $tong_cong['vat']              += $vat;
        $tong_cong['doanh_thu_chua_vat'] += $dt_chua_vat;
        $tong_cong['gia_von']          += $gia_von;
        $tong_cong['hoa_hong']         += $hoa_hong;
        $tong_cong['phi_nen_tang']     += $phi_nen_tang;
        $tong_cong['loi_nhuan']        += $loi_nhuan;
    }
    unset($row);
} catch (PDOException $e) {
    $loi = "Lỗi truy xuất dữ liệu: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <title>Quản Lý Kho Hàng & Vận Đơn - PHẠM NGỌC TV</title>
    <link rel="stylesheet" href="includes/admin-style.css">
    <style>
        body { font-family: Arial, sans-serif; background: #f8fafc; color: #334155; }
    </style>
</head>
<body>
    <?php require_once 'includes/menu-admin.php'; ?>
    <div class="khu-vuc-du-lieu">
        <div class="thanh-tren">
            <div>
                <strong>Trạm kho cho cơ sở</strong>
                <div class="page-subtitle">Quản lý sản phẩm, tồn kho và đơn hàng chờ giao trong một giao diện tập trung.</div>
            </div>
            <span class="pill">Cơ sở: <?= htmlspecialchars($_SESSION['ten_nguoi_dung'] ?? 'Cơ sở') ?></span>
        </div>
        <div class="noi-dung-chinh">
            <div class="wrap">
                <div class="page-shell">
                    <?php if ($thong_bao !== ''): ?><div class="alert alert-success"><?= htmlspecialchars($thong_bao) ?></div><?php endif; ?>
                    <?php if ($loi !== ''): ?><div class="alert alert-danger"><?= htmlspecialchars($loi) ?></div><?php endif; ?>

                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-label">Tổng sản phẩm</div>
                            <div class="stat-value"><?= number_format($summary_products, 0, ',', '.') ?></div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-label">Tổng tồn kho</div>
                            <div class="stat-value"><?= number_format($summary_stock, 0, ',', '.') ?></div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-label">Đơn hàng chờ giao</div>
                            <div class="stat-value"><?= number_format($summary_pending, 0, ',', '.') ?></div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-label">Giá trị tồn kho</div>
                            <div class="stat-value"><?= number_format($summary_value, 0, ',', '.') ?> đ</div>
                        </div>
                    </div>

                    <div class="tabs">
                        <a href="?tab=san-pham" class="<?= $active_tab === 'san-pham' ? 'active' : '' ?>">Quản lý sản phẩm</a>
                        <a href="?tab=ton-kho" class="<?= $active_tab === 'ton-kho' ? 'active' : '' ?>">Tồn kho</a>
                        <a href="?tab=don-hang" class="<?= $active_tab === 'don-hang' ? 'active' : '' ?>">Đơn hàng chờ giao</a>
                        <a href="?tab=loi-nhuan" class="<?= $active_tab === 'loi-nhuan' ? 'active' : '' ?>">Lợi nhuận</a>
                    </div>

                    <?php if ($active_tab === 'san-pham'): ?>
                        <div class="grid">
                            <div class="card">
                                <h2 style="margin-top:0;"><?= $edit_id > 0 ? 'Cập nhật sản phẩm' : 'Thêm sản phẩm mới' ?></h2>
                                <form method="POST" enctype="multipart/form-data">
                                    <input type="hidden" name="id_san_pham" value="<?= $edit_id > 0 ? (int)$edit_id : 0 ?>">
                                    <input type="hidden" name="luu_san_pham" value="1">
                                    <div class="row">
                                        <div>
                                            <label>Mã hiệu (SKU)</label>
                                            <input type="text" name="ma_hieu" value="<?= htmlspecialchars($san_pham_sua['ma_hieu'] ?? '') ?>" placeholder="SKU-001">
                                        </div>
                                        <div>
                                            <label>Tên sản phẩm</label>
                                            <input type="text" name="ten_san_pham" value="<?= htmlspecialchars($san_pham_sua['ten_san_pham'] ?? '') ?>" required>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div>
                                            <label>Danh mục</label>
                                            <select name="danh_muc">
                                                <option value="">-- Chọn danh mục --</option>
                                                <?php foreach ($danh_sach_danh_muc as $dm): ?>
                                                    <option value="<?= htmlspecialchars($dm['slug']) ?>" <?= (($san_pham_sua['danh_muc'] ?? '') === $dm['slug']) ? 'selected' : '' ?>><?= htmlspecialchars($dm['ten_danh_muc']) ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div>
                                            <label>Trạng thái</label>
                                            <select name="trang_thai">
                                                <option value="hien_thi" <?= (($san_pham_sua['trang_thai'] ?? 'hien_thi') === 'hien_thi') ? 'selected' : '' ?>>Hiển thị</option>
                                                <option value="an" <?= (($san_pham_sua['trang_thai'] ?? '') === 'an') ? 'selected' : '' ?>>Ẩn</option>
                                            </select>
                                        </div>
                                    </div>
                                    <label>Thông số kỹ thuật</label>
                                    <div class="specs-builder">
                                        <table id="specs_table" class="specs-table" style="width:100%;border-collapse:collapse;">
                                            <thead>
                                                <tr>
                                                    <th style="text-align:left;border-bottom:1px solid #e5e7eb;padding:6px">Thông số</th>
                                                    <th style="text-align:left;border-bottom:1px solid #e5e7eb;padding:6px">Giá trị</th>
                                                    <th style="width:48px;border-bottom:1px solid #e5e7eb;padding:6px"></th>
                                                </tr>
                                            </thead>
                                            <tbody></tbody>
                                        </table>
                                        <div style="margin-top:8px;">
                                            <button type="button" id="add_spec_btn" class="btn">Thêm hàng</button>
                                        </div>
                                        <input type="hidden" name="mo_ta" id="mo_ta_input" value="<?= htmlspecialchars($san_pham_sua['mo_ta'] ?? '') ?>">
                                        <div id="specs_preview" style="margin-top:8px;color:#475569;font-size:13px;"></div>
                                    </div>
                                    <div class="row">
                                        <div>
                                            <label>Hình ảnh từ máy</label>
                                            <input type="file" name="hinh_anh_file" accept="image/*">
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div>
                                            <label>Giá gốc (giá nhập)</label>
                                            <input type="number" name="gia_goc" value="<?= (int)($san_pham_sua['gia_goc'] ?? 0) ?>" required>
                                        </div>
                                        <div>
                                            <label>Số lượng tồn ban đầu</label>
                                            <input type="number" name="so_luong_ton" value="<?= (int)($san_pham_sua['so_luong_ton'] ?? 0) ?>">
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div>
                                            <label>Vị trí kho ban đầu</label>
                                            <input type="text" name="vi_tri_kho" value="<?= htmlspecialchars($san_pham_sua['vi_tri_kho'] ?? '') ?>" placeholder="Ví dụ: Kệ A3, Ngăn 2">
                                        </div>
                                    </div>
                                    <!-- Flags moved to store setup form -->
                                    <div class="row">
                                        <button type="submit" class="btn btn-primary"><?= $edit_id > 0 ? 'Cập nhật' : 'Thêm sản phẩm' ?></button>
                                        <?php if ($edit_id > 0): ?><a class="btn btn-secondary" href="?tab=san-pham">Hủy sửa</a><?php endif; ?>
                                    </div>
                                </form>
                            </div>
                            <div class="card">
                                <h2 style="margin-top:0;">Quản lý danh mục sản phẩm</h2>
                                <form method="POST">
                                    <input type="hidden" name="luu_danh_muc" value="1">
                                    <input type="hidden" name="id_danh_muc" value="<?= (int)($danh_muc_sua['id'] ?? 0) ?>">
                                    <div class="row">
                                        <div>
                                            <label>Tên danh mục</label>
                                            <input type="text" name="ten_danh_muc" value="<?= htmlspecialchars($danh_muc_sua['ten_danh_muc'] ?? '') ?>" placeholder="Ví dụ: Đồ thủ công" required>
                                        </div>
                                        <div>
                                            <label>Slug</label>
                                            <input type="text" name="slug" value="<?= htmlspecialchars($danh_muc_sua['slug'] ?? '') ?>" placeholder="do_thu_cong">
                                        </div>
                                    </div>
                                    <div class="row">
                                        <button type="submit" class="btn btn-primary"><?= $edit_category_id > 0 ? 'Cập nhật danh mục' : 'Thêm danh mục' ?></button>
                                        <?php if ($edit_category_id > 0): ?><a class="btn btn-secondary" href="?tab=san-pham">Hủy sửa</a><?php endif; ?>
                                    </div>
                                </form>
                                <table class="table-admin">
                                    <thead><tr><th>Tên danh mục</th><th>Slug</th><th>Tác vụ</th></tr></thead>
                                    <tbody>
                                        <?php foreach ($danh_sach_danh_muc as $dm): ?>
                                            <tr>
                                                <td><?= htmlspecialchars($dm['ten_danh_muc']) ?></td>
                                                <td><?= htmlspecialchars($dm['slug']) ?></td>
                                                <td>
                                                    <div class="row" style="margin:0; gap:6px;">
                                                        <a class="btn btn-secondary" href="?tab=san-pham&edit_category_id=<?= (int)$dm['id'] ?>">Sửa</a>
                                                        <form method="POST" style="display:inline;" onsubmit="return confirm('Xóa danh mục này?');">
                                                            <input type="hidden" name="id_danh_muc" value="<?= (int)$dm['id'] ?>">
                                                            <input type="hidden" name="xoa_danh_muc" value="1">
                                                            <button type="submit" class="btn btn-danger">Xóa</button>
                                                        </form>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <div class="card card-full">
                                <h2 style="margin-top:0;">Danh sách sản phẩm</h2>
                                <form method="GET" class="row" style="margin-bottom:12px;">
                                    <input type="hidden" name="tab" value="san-pham">
                                    <div>
                                        <label>Tìm kiếm</label>
                                        <input type="text" name="search_san_pham" value="<?= htmlspecialchars($search_san_pham) ?>" placeholder="Tên, SKU, mô tả">
                                    </div>
                                    <div>
                                        <label>Danh mục</label>
                                        <select name="filter_danh_muc">
                                            <option value="">Tất cả</option>
                                            <?php foreach ($danh_sach_danh_muc as $dm): ?>
                                                <option value="<?= htmlspecialchars($dm['slug']) ?>" <?= $filter_danh_muc === $dm['slug'] ? 'selected' : '' ?>><?= htmlspecialchars($dm['ten_danh_muc']) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div>
                                        <label>Trạng thái</label>
                                        <select name="filter_trang_thai">
                                            <option value="">Tất cả</option>
                                            <option value="hien_thi" <?= $filter_trang_thai === 'hien_thi' ? 'selected' : '' ?>>Hiển thị</option>
                                            <option value="an" <?= $filter_trang_thai === 'an' ? 'selected' : '' ?>>Ẩn</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label>&nbsp;</label>
                                        <button type="submit" class="btn btn-primary">Lọc</button>
                                    </div>
                                </form>
                                <table class="table-admin">
                                    <thead>
                                        <tr><th>Ảnh</th><th>SKU</th><th>Sản phẩm</th><th>Danh mục</th><th>Giá gốc</th><th>Tồn kho</th><th>Tác vụ</th></tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($danh_sach_san_pham as $sp): ?>
                                            <?php $anh_sp = trim((string)($sp['hinh_anh'] ?? '')); ?>
                                            <?php $ton = (int)($sp['ton_kho_hien_tai'] ?? 0); ?>
                                            <tr>
                                                <td>
                                                    <?php if ($anh_sp !== ''): ?>
                                                        <img src="<?= htmlspecialchars($anh_sp) ?>" alt="Ảnh sản phẩm" class="product-thumb">
                                                    <?php else: ?>
                                                        <div class="product-thumb product-thumb-empty">No image</div>
                                                    <?php endif; ?>
                                                </td>
                                                <td><?= htmlspecialchars($sp['ma_hieu'] ?? '') ?></td>
                                                <td><strong><?= htmlspecialchars($sp['ten_san_pham']) ?></strong></td>
                                                <td><?= htmlspecialchars($category_lookup[$sp['danh_muc']] ?? ($sp['danh_muc'] ?? '')) ?></td>
                                                <td><?= number_format((int)$sp['gia_goc'], 0, ',', '.') ?> đ</td>
                                                <td>
                                                    <span class="pill" style="background:<?= $ton <= 0 ? '#fee2e2;color:#b91c1c' : ($ton <= 5 ? '#fef9c3;color:#854d0e' : '#dcfce7;color:#166534') ?>">
                                                        <?= $ton ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <div class="row" style="margin:0; gap:6px;">
                                                        <a class="btn btn-secondary" href="?tab=san-pham&edit_id=<?= (int)$sp['id'] ?>">Sửa</a>
                                                        <a class="btn btn-success" href="?tab=ton-kho&prefill_product=<?= (int)$sp['id'] ?>">Nhập kho</a>
                                                        <button type="button" class="btn btn-info view-specs" data-spec="<?= htmlspecialchars(strip_tags($sp['mo_ta'] ?? '', '<table><thead><tbody><tfoot><tr><td><th>'), ENT_QUOTES) ?>">Xem chi tiết</button>
                                                        <form method="POST" style="display:inline;" onsubmit="return confirm('Xóa sản phẩm này khỏi kho?');">
                                                            <input type="hidden" name="id_san_pham" value="<?= (int)$sp['id'] ?>">
                                                            <input type="hidden" name="xoa_san_pham" value="1">
                                                            <button type="submit" class="btn btn-danger">Xóa</button>
                                                        </form>
                                                    </div>
                                                </td>

                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    <?php elseif ($active_tab === 'ton-kho'): ?>
                        <div class="grid">
                            <div class="card">
                                <h2 style="margin-top:0;">Nhập / xuất tồn kho</h2>
                                <form method="POST">
                                    <input type="hidden" name="cap_nhat_ton_kho" value="1">
                                    <label>Sản phẩm</label>
                                    <select name="id_san_pham" required>
                                        <option value="">-- Chọn sản phẩm --</option>
                                        <?php foreach ($danh_sach_san_pham as $sp): ?>
                                            <option value="<?= (int)$sp['id'] ?>" <?= $prefill_product === (int)$sp['id'] ? 'selected' : '' ?>><?= htmlspecialchars($sp['ma_hieu'] ?: 'SKU') ?> - <?= htmlspecialchars($sp['ten_san_pham']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <label>Loại thao tác</label>
                                    <select name="loai_thao_tac">
                                        <option value="nhap" <?= $prefill_action === 'nhap' ? 'selected' : '' ?>>Nhập kho</option>
                                        <option value="xuat" <?= $prefill_action === 'xuat' ? 'selected' : '' ?>>Xuất kho</option>
                                    </select>
                                    <label>Số lượng</label>
                                    <input type="number" name="so_luong" min="1" value="1" required>
                                    <label>Vị trí kho</label>
                                    <input type="text" name="vi_tri_kho" placeholder="Ví dụ: Kệ A3, Ngăn 2">
                                    <button type="submit" class="btn btn-success">Lưu thay đổi kho</button>
                                </form>
                            </div>
                            <div class="card">
                                <h2 style="margin-top:0;">Tồn kho hiện tại</h2>
                                <form method="GET" class="row" style="margin-bottom:12px;">
                                    <input type="hidden" name="tab" value="ton-kho">
                                    <div>
                                        <label>Tìm theo SKU / tên</label>
                                        <input type="text" name="search_kho" value="<?= htmlspecialchars($search_kho) ?>" placeholder="Nhập tên hoặc SKU">
                                    </div>
                                    <div>
                                        <label>&nbsp;</label>
                                        <button type="submit" class="btn btn-primary">Lọc kho</button>
                                    </div>
                                </form>
                                <table class="table-admin">
                                    <thead><tr><th>SKU</th><th>Sản phẩm</th><th>Vị trí</th><th>Số lượng</th><th>Giá bán</th></tr></thead>
                                    <tbody>
                                        <?php if (!empty($ton_kho_co_so)): ?>
                                            <?php foreach ($ton_kho_co_so as $kho): ?>
                                                <tr>
                                                    <td><?= htmlspecialchars($kho['ma_hieu'] ?? '') ?></td>
                                                    <td><strong><?= htmlspecialchars($kho['ten_san_pham']) ?></strong></td>
                                                    <td><?= htmlspecialchars($kho['vi_tri_kho'] ?? 'Chưa xác định') ?></td>
                                                    <td><span class="pill"><?= (int)$kho['so_luong_ton'] ?></span></td>
                                                    <td>
                                                        <?= number_format((int)$kho['gia_goc'], 0, ',', '.') ?> đ<br>
                                                        <div class="row" style="margin:6px 0 0; gap:6px;">
                                                            <a class="btn btn-success" href="?tab=ton-kho&prefill_product=<?= (int)$kho['id_san_pham'] ?>&prefill_action=nhap">Nhập</a>
                                                            <a class="btn btn-danger" href="?tab=ton-kho&prefill_product=<?= (int)$kho['id_san_pham'] ?>&prefill_action=xuat">Xuất</a>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <tr><td colspan="5" class="muted">Chưa có dữ liệu tồn kho cho cơ sở này.</td></tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                            <div class="card">
                                <h2 style="margin-top:0;">Sản phẩm sắp hết</h2>
                                <?php if (!empty($san_pham_sap_het)): ?>
                                    <ul class="muted" style="padding-left: 18px; margin: 0;">
                                        <?php foreach ($san_pham_sap_het as $sp_low): ?>
                                            <li><strong><?= htmlspecialchars($sp_low['ten_san_pham']) ?></strong> — SKU <?= htmlspecialchars($sp_low['ma_hieu'] ?? '') ?> — còn <span class="pill"><?= (int)$sp_low['so_luong_ton'] ?></span></li>
                                        <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <p class="muted">Không có sản phẩm nào sắp hết tồn kho.</p>
                                <?php endif; ?>
                            </div>
                            <div class="card">
                                <h2 style="margin-top:0;">Lịch sử nhập/xuất kho</h2>
                                <table class="table-admin">
                                    <thead>
                                        <tr><th>Thời gian</th><th>Sản phẩm</th><th>Loại</th><th>Số lượng</th><th>Vị trí</th><th>Ghi chú</th></tr>
                                    </thead>
                                    <tbody>
                                        <?php if (!empty($lich_su_kho)): ?>
                                            <?php foreach ($lich_su_kho as $ls): ?>
                                                <tr>
                                                    <td><?= htmlspecialchars(date('d/m/Y H:i', strtotime($ls['ngay_tao']))) ?></td>
                                                    <td><strong><?= htmlspecialchars($ls['ten_san_pham']) ?></strong><br><span class="muted">SKU: <?= htmlspecialchars($ls['ma_hieu'] ?? '') ?></span></td>
                                                    <td><?= $ls['loai_thao_tac'] === 'xuat' ? 'Xuất kho' : 'Nhập kho' ?></td>
                                                    <td><span class="pill"><?= (int)$ls['so_luong'] ?></span></td>
                                                    <td><?= htmlspecialchars($ls['vi_tri_kho'] ?? '-') ?></td>
                                                    <td><?= htmlspecialchars($ls['ghi_chu'] ?? '-') ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <tr><td colspan="6" class="muted">Chưa có lịch sử nhập/xuất kho.</td></tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    <?php elseif ($active_tab === 'don-hang'): ?>
                        <div class="card">
                            <h2 style="margin-top:0;">Đơn hàng chờ giao</h2>
                            <?php if (!empty($don_hang_cho)): ?>

                                <?php foreach ($don_hang_cho as $don): ?>
                                    <div class="order-item">
                                        <div>
                                            <strong><?= htmlspecialchars($don['ten_san_pham']) ?></strong><br>
                                            <span class="muted">Khách: <?= htmlspecialchars($don['ten_khach_hang']) ?> • <?= htmlspecialchars($don['so_dien_thoai']) ?></span><br>
                                            <span class="muted">Địa chỉ: <?= htmlspecialchars($don['dia_chi_giao']) ?></span>
                                        </div>
                                        <form method="POST">
                                            <input type="hidden" name="id_don_hang" value="<?= (int)$don['id'] ?>">
                                            <input type="hidden" name="xac_nhan_giao_hang" value="1">
                                            <button type="submit" class="btn btn-success">Xác nhận giao hàng</button>
                                        </form>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <p class="muted">Không có đơn hàng nào đang chờ giao tại cơ sở này.</p>
                            <?php endif; ?>
                        </div>
                    <?php elseif ($active_tab === 'loi-nhuan'): ?>
                        <div class="card card-full">
                            <div style="display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:12px; margin-bottom:16px;">
                                <h2 style="margin:0;">📊 Báo cáo lợi nhuận</h2>
                                <form method="GET" style="display:flex; align-items:center; gap:8px;">
                                    <input type="hidden" name="tab" value="loi-nhuan">
                                    <label style="font-weight:600; font-size:13px;">Tháng:</label>
                                    <input type="month" name="loc_thang" value="<?= htmlspecialchars($loc_thang) ?>" style="padding:6px 10px; border:1.5px solid #e2e8f0; border-radius:8px; font-size:13px;">
                                    <button type="submit" class="btn btn-primary">Xem</button>
                                </form>
                            </div>

                            <?php if (!empty($bao_cao_loi_nhuan)): ?>
                                <!-- Thẻ tổng quan -->
                                <div style="display:grid; grid-template-columns:repeat(auto-fill,minmax(160px,1fr)); gap:12px; margin-bottom:20px;">
                                    <div style="background:#f0fdf4; border-radius:12px; padding:14px 16px;">
                                        <div style="font-size:11px; font-weight:700; color:#15803d; text-transform:uppercase; margin-bottom:4px;">Doanh thu (có VAT)</div>
                                        <div style="font-size:1.1rem; font-weight:900; color:#166534;"><?= number_format($tong_cong['doanh_thu_vat'], 0, ',', '.') ?> đ</div>
                                    </div>
                                    <div style="background:#fef9c3; border-radius:12px; padding:14px 16px;">
                                        <div style="font-size:11px; font-weight:700; color:#854d0e; text-transform:uppercase; margin-bottom:4px;">Thuế VAT (10%)</div>
                                        <div style="font-size:1.1rem; font-weight:900; color:#92400e;"><?= number_format($tong_cong['vat'], 0, ',', '.') ?> đ</div>
                                    </div>
                                    <div style="background:#eff6ff; border-radius:12px; padding:14px 16px;">
                                        <div style="font-size:11px; font-weight:700; color:#1d4ed8; text-transform:uppercase; margin-bottom:4px;">Doanh thu (chưa VAT)</div>
                                        <div style="font-size:1.1rem; font-weight:900; color:#1e40af;"><?= number_format($tong_cong['doanh_thu_chua_vat'], 0, ',', '.') ?> đ</div>
                                    </div>
                                    <div style="background:#fef2f2; border-radius:12px; padding:14px 16px;">
                                        <div style="font-size:11px; font-weight:700; color:#b91c1c; text-transform:uppercase; margin-bottom:4px;">Giá vốn</div>
                                        <div style="font-size:1.1rem; font-weight:900; color:#991b1b;"><?= number_format($tong_cong['gia_von'], 0, ',', '.') ?> đ</div>
                                    </div>
                                    <div style="background:#fdf4ff; border-radius:12px; padding:14px 16px;">
                                        <div style="font-size:11px; font-weight:700; color:#7e22ce; text-transform:uppercase; margin-bottom:4px;">Hoa hồng</div>
                                        <div style="font-size:1.1rem; font-weight:900; color:#6b21a8;"><?= number_format($tong_cong['hoa_hong'], 0, ',', '.') ?> đ</div>
                                    </div>
                                    <div style="background:#fff7ed; border-radius:12px; padding:14px 16px;">
                                        <div style="font-size:11px; font-weight:700; color:#c2410c; text-transform:uppercase; margin-bottom:4px;">Phí nền tảng</div>
                                        <div style="font-size:1.1rem; font-weight:900; color:#9a3412;"><?= number_format($tong_cong['phi_nen_tang'], 0, ',', '.') ?> đ</div>
                                    </div>
                                    <div style="background:<?= $tong_cong['loi_nhuan'] >= 0 ? '#f0fdf4' : '#fef2f2' ?>; border-radius:12px; padding:14px 16px; border:2px solid <?= $tong_cong['loi_nhuan'] >= 0 ? '#86efac' : '#fca5a5' ?>;">
                                        <div style="font-size:11px; font-weight:700; color:<?= $tong_cong['loi_nhuan'] >= 0 ? '#15803d' : '#b91c1c' ?>; text-transform:uppercase; margin-bottom:4px;">Lợi nhuận</div>
                                        <div style="font-size:1.2rem; font-weight:900; color:<?= $tong_cong['loi_nhuan'] >= 0 ? '#166534' : '#991b1b' ?>;"><?= number_format($tong_cong['loi_nhuan'], 0, ',', '.') ?> đ</div>
                                    </div>
                                </div>

                                <!-- Bảng chi tiết -->
                                <div style="overflow-x:auto;">
                                <table class="table-admin" style="font-size:13px;">
                                    <thead>
                                        <tr>
                                            <th>Sản phẩm</th>
                                            <th style="text-align:center;">SL bán</th>
                                            <th style="text-align:right;">DT có VAT</th>
                                            <th style="text-align:right;">Thuế VAT</th>
                                            <th style="text-align:right;">DT chưa VAT</th>
                                            <th style="text-align:right;">Giá vốn</th>
                                            <th style="text-align:right;">Hoa hồng</th>
                                            <th style="text-align:right;">Phí NTảng</th>
                                            <th style="text-align:right;">Lợi nhuận</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($bao_cao_loi_nhuan as $r): ?>
                                        <tr>
                                            <td>
                                                <strong><?= htmlspecialchars($r['ten_san_pham']) ?></strong>
                                                <?php if (!empty($r['ma_hieu'])): ?><br><span class="muted">SKU: <?= htmlspecialchars($r['ma_hieu']) ?></span><?php endif; ?>
                                            </td>
                                            <td style="text-align:center;"><span class="pill"><?= (int)$r['tong_so_luong'] ?></span></td>
                                            <td style="text-align:right;"><?= number_format($r['dt_vat'], 0, ',', '.') ?></td>
                                            <td style="text-align:right; color:#92400e;"><?= number_format($r['vat'], 0, ',', '.') ?></td>
                                            <td style="text-align:right; color:#1e40af;"><?= number_format($r['dt_chua_vat'], 0, ',', '.') ?></td>
                                            <td style="text-align:right; color:#991b1b;"><?= number_format($r['gia_von'], 0, ',', '.') ?></td>
                                            <td style="text-align:right; color:#6b21a8;"><?= number_format($r['hoa_hong'], 0, ',', '.') ?></td>
                                            <td style="text-align:right; color:#9a3412;"><?= number_format($r['phi_nen_tang_tong'], 0, ',', '.') ?></td>
                                            <td style="text-align:right; font-weight:800; color:<?= $r['loi_nhuan'] >= 0 ? '#166534' : '#991b1b' ?>;">
                                                <?= number_format($r['loi_nhuan'], 0, ',', '.') ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                    <tfoot>
                                        <tr style="font-weight:800; background:#f8fafc;">
                                            <td>Tổng cộng</td>
                                            <td></td>
                                            <td style="text-align:right;"><?= number_format($tong_cong['doanh_thu_vat'], 0, ',', '.') ?></td>
                                            <td style="text-align:right; color:#92400e;"><?= number_format($tong_cong['vat'], 0, ',', '.') ?></td>
                                            <td style="text-align:right; color:#1e40af;"><?= number_format($tong_cong['doanh_thu_chua_vat'], 0, ',', '.') ?></td>
                                            <td style="text-align:right; color:#991b1b;"><?= number_format($tong_cong['gia_von'], 0, ',', '.') ?></td>
                                            <td style="text-align:right; color:#6b21a8;"><?= number_format($tong_cong['hoa_hong'], 0, ',', '.') ?></td>
                                            <td style="text-align:right; color:#9a3412;"><?= number_format($tong_cong['phi_nen_tang'], 0, ',', '.') ?></td>
                                            <td style="text-align:right; font-weight:900; font-size:1rem; color:<?= $tong_cong['loi_nhuan'] >= 0 ? '#166534' : '#991b1b' ?>;">
                                                <?= number_format($tong_cong['loi_nhuan'], 0, ',', '.') ?>
                                            </td>
                                        </tr>
                                    </tfoot>
                                </table>
                                </div>
                                <p class="muted" style="margin-top:10px; font-size:12px;">* Hoa hồng = Doanh thu chưa VAT × tỷ lệ affiliate. Lợi nhuận = DT chưa VAT − Giá vốn − Hoa hồng − Phí nền tảng.</p>
                            <?php else: ?>
                                <p class="muted">Chưa có đơn hàng giao thành công trong tháng <?= htmlspecialchars($loc_thang) ?>.</p>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</body>
<script>
// Initialize specs builder
// Modal handler for viewing full specs
(function(){
    var initialHtml = <?php echo json_encode($san_pham_sua['mo_ta'] ?? ''); ?>;
    var tableBody = document.querySelector('#specs_table tbody');
    var addBtn = document.getElementById('add_spec_btn');
    var hiddenInput = document.getElementById('mo_ta_input');
    var preview = document.getElementById('specs_preview');

    function addRow(key, val) {
        var tr = document.createElement('tr');
        tr.innerHTML = '<td style="padding:6px;border-bottom:1px solid #f1f5f9;"><input type="text" class="spec-key" style="width:100%;" value="'+(key||'')+'"></td>' +
                       '<td style="padding:6px;border-bottom:1px solid #f1f5f9;"><input type="text" class="spec-val" style="width:100%;" value="'+(val||'')+'"></td>' +
                       '<td style="padding:6px;border-bottom:1px solid #f1f5f9;text-align:center;">' +
                       '<button type="button" class="btn btn-danger btn-sm spec-remove">✕</button></td>';
        tableBody.appendChild(tr);
        tr.querySelector('.spec-remove').addEventListener('click', function(){ tr.remove(); updatePreview(); });
        tr.querySelectorAll('input').forEach(function(inp){ inp.addEventListener('input', updatePreview); });
        updatePreview();
    }

    function updatePreview(){
        var rows = tableBody.querySelectorAll('tr');
        if (rows.length === 0) {
            preview.innerHTML = '<div class="muted">Chưa có thông số nào. Nhấn "Thêm hàng" để bắt đầu.</div>';
            hiddenInput.value = '';
            return;
        }
        var html = '<table style="width:100%;border-collapse:collapse;">';
        for (var i=0;i<rows.length;i++){
            var k = rows[i].querySelector('.spec-key').value.trim();
            var v = rows[i].querySelector('.spec-val').value.trim();
            if (k === '' && v === '') continue;
            html += '<tr><td style="border:1px solid #e5e7eb;padding:6px;vertical-align:top;">'+escapeHtml(k)+'</td><td style="border:1px solid #e5e7eb;padding:6px;vertical-align:top;">'+escapeHtml(v)+'</td></tr>';
        }
        html += '</table>';
        preview.innerHTML = html;
        hiddenInput.value = html;
    }

    function escapeHtml(str){
        return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }

    addBtn.addEventListener('click', function(){ addRow('',''); });

    // Try to parse initialHtml as table rows
    if (initialHtml && initialHtml.indexOf('<table') !== -1) {
        var tmp = document.createElement('div');
        tmp.innerHTML = initialHtml;
        var trs = tmp.querySelectorAll('tr');
        if (trs.length > 0) {
            trs.forEach(function(tr){
                var tds = tr.querySelectorAll('td');
                var kk = tds[0] ? (tds[0].textContent||'') : '';
                var vv = tds[1] ? (tds[1].textContent||'') : '';
                addRow(kk, vv);
            });
        }
    } else if (hiddenInput.value && hiddenInput.value.trim() !== '') {
        // If there is raw text (not table), place into a single row
        addRow('Chi tiết', hiddenInput.value);
    }

    // Ensure preview updated before submit
    var forms = document.querySelectorAll('form');
    forms.forEach(function(f){
        f.addEventListener('submit', function(){ updatePreview(); });
    });
})();
</script>

<!-- Specs modal -->
<div id="specs_modal" style="display:none;position:fixed;inset:0;background:rgba(2,6,23,0.6);align-items:center;justify-content:center;z-index:9999;">
    <div style="background:#fff;border-radius:8px;max-width:900px;width:95%;max-height:80vh;overflow:auto;padding:16px;box-shadow:0 8px 24px rgba(15,23,42,0.2);margin:auto;">
        <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:8px;">
            <strong>Thông số kỹ thuật</strong>
            <button id="specs_close" class="btn btn-secondary">Đóng</button>
        </div>
        <div id="specs_modal_content" style="color:#0f172a;font-size:14px;line-height:1.4;"></div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function(){
    var modal = document.getElementById('specs_modal');
    var content = document.getElementById('specs_modal_content');
    var closeBtn = document.getElementById('specs_close');
    document.querySelectorAll('.view-specs').forEach(function(btn){
        btn.addEventListener('click', function(){
            var raw = btn.getAttribute('data-spec') || '';
            content.innerHTML = raw;
            modal.style.display = 'flex';
        });
    });
    closeBtn.addEventListener('click', function(){ modal.style.display = 'none'; });
    modal.addEventListener('click', function(e){ if (e.target === modal) modal.style.display = 'none'; });
});
</script>
</html>