<?php
session_start();
date_default_timezone_set('Asia/Ho_Chi_Minh');

// Kiểm tra quyền truy cập (nếu cần)
// if (!isset($_SESSION['matruongmn'])) { header("location:dangnhap.php"); exit; }

require("Connection.php");

// 1. Khởi tạo biến an toàn
$kieu = isset($_GET["kieu"]) ? $_GET["kieu"] : "";
$madxgt = isset($_GET["madx"]) ? (int)$_GET["madx"] : 0; // Ép kiểu int luôn cho an toàn
$makl = isset($_POST["khoilop"]) ? $_POST["khoilop"] : "";
$malh = isset($_POST["malh"]) ? $_POST["malh"] : ""; // Biến dùng cho nút Thoát

// 2. Logic XÓA (Giữ nguyên logic cũ: Lấy thông tin trước -> Xóa bảng chính -> Xóa bảng phụ)
if ($kieu == "D" && $madxgt > 0) {
    
    // Bước 1: Lấy thông tin đề xuất để xóa bên bảng solieugt
    $sql_check = "SELECT * FROM dexuatgiaotrinh WHERE madx=" . $madxgt;
    $res_check = mysqli_query($link, $sql_check);
    
    if ($res_check && mysqli_num_rows($res_check) > 0) {
        $row_check = mysqli_fetch_array($res_check);
        $ngdx_del = $row_check["ngaydexuat"];
        $matruong_del = $row_check["matruongmn"];
        $malop_del = $row_check["malopmn"];

        // Bước 2: Xóa bảng chính
        $sql_del_main = "DELETE FROM dexuatgiaotrinh WHERE madx=" . $madxgt;
        mysqli_query($link, $sql_del_main);

        // Bước 3: Xóa bảng phụ (solieugt) theo logic cũ
        // Lưu ý: Cần escape dữ liệu vì lấy từ DB ra đôi khi vẫn cần an toàn
        $sql_del_sub = "DELETE FROM solieugt WHERE matruongmn='" . $matruong_del . "' AND malopmn=" . $malop_del . " AND ngaydx='" . $ngdx_del . "'";
        mysqli_query($link, $sql_del_sub);
    }
    
    // Redirect để tránh resubmit
    header("Location: dexuatgiaotrinhnew.php");
    exit();
}

// --- HÀM HỖ TRỢ SINH OPTION (TỐI ƯU CODE) ---
function renderOptions($prefix, $max_number) {
    echo '<option value="">---</option>'; // Option rỗng mặc định
    for ($i = 1; $i <= $max_number; $i++) {
        // Hàm sprintf('%03d', $i) sẽ biến số 1 thành 001, 10 thành 010
        $code = $prefix . sprintf('%03d', $i);
        echo "<option value=\"$code\">$code</option>";
    }
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<HTML>
<HEAD>
    <Title>De xuat giao trinh</Title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link href="css/default.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        body { margin: 0px; }
        .style7 { font-size: 16pt; color: #CC0000; font-weight: bold; font-family: Arial, Helvetica, sans-serif; }
    </style>
</HEAD>
<body>
    <form name="f1" method="POST">
        <div align="center"><span class="style7">ĐỀ XUẤT GIÁO TRÌNH<br />
            <?php
            $hotengv = "";
            if (isset($_SESSION["matruongmn"])) {
                $matruong_safe = mysqli_real_escape_string($link, $_SESSION["matruongmn"]);
                $sql1 = "select tentruongmn from truongmn where matruongmn='" . $matruong_safe . "'";
                $result1 = mysqli_query($link, $sql1);
                if ($result1 && mysqli_num_rows($result1) > 0) {
                    while ($row1 = mysqli_fetch_array($result1)) {
                        $hotengv = $row1["tentruongmn"];
                    }
                }
            }
            echo "<font face='Arial'>$hotengv</font>";
            ?>
        </span></div>
        <br />

        <div align="center">
            <table width="70%" align="center" cellspacing="0" class="khungbao1">
                <tr>
                    <td width="226">
                        <font color="#800000" size="3" face="Arial">Chọn lớp :</font>
                        <select name="khoilop" class="box1">
                            <option value="">Tất cả</option>
                            <?php
                            if (isset($_SESSION["matruongmn"])) {
                                $sql1 = "select * from lopmn where matruongmn='" . $matruong_safe . "' order by tenlopmn";
                                $result1 = mysqli_query($link, $sql1);
                                if ($result1 && mysqli_num_rows($result1) > 0) {
                                    while ($row1 = mysqli_fetch_array($result1)) {
                                        $malop = $row1["malopmn"];
                                        $tenlop = $row1["tenlopmn"];
                                        echo "<option value=\"$malop\">$tenlop</option>";
                                    }
                                }
                            }
                            ?>
                        </select>
                    </td>
                    <td width="238">
                        <font color="#800000" face="Arial" size="3">Số lượng bé:
                            <input name="soluongbe" type="text" class="box1" size="7" maxlength="5" onkeypress="return checknum(event);" />
                        </font>
                    </td>
                    <td width="391">
                        <font color="#800000" size="3" face="Arial">Người đề xuất:
                            <input name="nguoidx" type="text" class="box1" size="20" />
                        </font>
                    </td>
                </tr>
            </table>
            <p><font color="#f00aa0" size="5" face="Arial"><br />Giáo trình đề xuất</font></p>
        </div>

        <table width="100%" align="center" cellspacing="0" class="khungbao1">
            
            <tr>
                <td width="9%" align="center" class="dkta1"><p align="center"><font color="#ff0000" face="Arial" size="4">Mã K3A</font></p></td>
                <?php for($k=1; $k<=10; $k++) { // Loop tạo 10 ô select ?>
                <td align="left" class="dkta1">
                    <select name="k3a<?php echo $k; ?>" class="box1">
                        <?php renderOptions('K3A', 102); ?>
                    </select>
                </td>
                <?php } ?>
            </tr>

            <?php $currentDate = date("Y-m-d H:i:s"); ?>

            <tr>
                <td align="center" class="dkta1"><p align="center"><font color="#ff0000" face="Arial" size="4">Mã K2B</font></p></td>
                <?php for($k=1; $k<=10; $k++) { ?>
                <td align="left" class="dkta1">
                    <select name="k2b<?php echo $k; ?>" class="box1">
                        <?php renderOptions('K2B', 99); ?>
                    </select>
                </td>
                <?php } ?>
                <input name="ngaydx" type="hidden" value="<?php echo $currentDate; ?>" />
            </tr>

            <tr>
                <td align="center" class="dkta1"><p align="center"><font color="#ff0000" face="Arial" size="4">Mã K1C</font></p></td>
                <?php for($k=1; $k<=10; $k++) { ?>
                <td align="left" class="dkta1">
                    <select name="k1c<?php echo $k; ?>" class="box1">
                        <?php renderOptions('K1C', 98); ?>
                    </select>
                </td>
                <?php } ?>
            </tr>

            <tr>
                <td align="center" class="dkta1"><p align="center"><font color="#ff0000" face="Arial" size="4">Mã L</font></p></td>
                <?php for($k=1; $k<=10; $k++) { ?>
                <td align="left" class="dkta1">
                    <select name="l<?php echo $k; ?>" class="box1">
                        <?php renderOptions('L', 45); // File gốc max là L045 ?>
                    </select>
                </td>
                <?php } ?>
            </tr>

            <tr>
                <td align="center" class="dkta1"><p align="center"><font color="#ff0000" face="Arial" size="4">Mã D</font></p></td>
                <?php for($k=1; $k<=10; $k++) { ?>
                <td align="left" class="dkta1">
                    <select name="d<?php echo $k; ?>" class="box1">
                        <?php renderOptions('D', 30); ?>
                    </select>
                </td>
                <?php } ?>
            </tr>

            <tr>
                <td align="center" class="dkta1"><p align="center"><font color="#ff0000" face="Arial" size="4">Mã N</font></p></td>
                <?php for($k=1; $k<=10; $k++) { ?>
                <td align="left" class="dkta1">
                    <select name="n<?php echo $k; ?>" class="box1">
                        <?php renderOptions('N', 96); ?>
                    </select>
                </td>
                <?php } ?>
            </tr>

            <tr>
                <td align="center" class="dkta1">&nbsp;</td>
                <td colspan="10" align="center" class="dkta1">
                    <font color="#660000" face="Arial" size="4"><strong><em>Ghi chú :</em></strong></font>
                    <font color="#800000" size="3" face="Arial">
                        <input name="ghichu" type="text" class="box1" size="50" />
                    </font>
                </td>
            </tr>
            <input name="mtmn" type="hidden" value="<?php echo isset($_SESSION["matruongmn"]) ? $_SESSION["matruongmn"] : ''; ?>" />
        </table>

        <p align="center">
            <br />
            <input type="button" value="Cập nhật" name="cmd1" onclick="kt()" />
            &nbsp;&nbsp;
            <input name="cmd12" type="button" value="Thoát" onclick="javascript:window.location.href = 'logout.php';" />
            <input type="hidden" value="<?php echo $malh; ?>" name="malh" />
        </p>

        <p align="center">&nbsp;</p>
        <p align="center" class="style7"><a name="xemgt" id="xemgt"></a>DANH SÁCH GIÁO TRÌNH ĐÃ ĐỀ XUẤT</p>

        <table width="100%" cellspacing="0" class="khungbao1">
            <tr>
                <td width="5%" align="center" class="dkta1"><p align="center"><font color="#800000" size="2" face="Arial">XÓA</font></p></td>
                <td width="5%" align="center" class="dkta1"><p align="center"><font color="#800000" face="Arial" size="2">MãQL</font></p></td>
                <td width="14%" align="center" class="dkta1"><p align="center"><font color="#800000" face="Arial" size="2">Ngày đề xuất</font></p></td>
                <td width="7%" align="center" class="dkta1"><p align="center"><font color="#800000" face="Arial" size="2">Lớp</font></p></td>
                <td width="10%" align="center" class="dkta1"><p align="center"><font color="#800000" face="Arial" size="2">Số lượng bé</font></p></td>
                <td width="41%" align="center" class="dkta1"><p align="center"><font color="#800000" face="Arial" size="2">Giáo trình đã đề xuất</font></p></td>
                <td width="10%" align="center" class="dkta1"><p align="center"><font color="#800000" size="2" face="Arial">Người đề xuất</font></p></td>
                <td width="6%" align="center" class="dkta1"><p align="center"><font color="#800000" face="Arial" size="2">Trạng thái</font></p></td>
                <td width="7%" align="center" class="dkta1"><p align="center"><font color="#800000" face="Arial" size="2">Trường</font></p></td>
            </tr>

            <?php
            $chuoitim = "";
            $matruong_safe = isset($_SESSION["matruongmn"]) ? mysqli_real_escape_string($link, $_SESSION["matruongmn"]) : "";

            if ($makl <> "") {
                $makl_safe = mysqli_real_escape_string($link, $makl);
                $chuoitim = $chuoitim . " b.khoilop like N'%" . $makl_safe . "%' and ";
            }

            if ($chuoitim <> "")
                $sql4 = "SELECT a.*,b.khoilop, b.tenlopmn FROM dexuatgiaotrinh a , lopmn b where " . $chuoitim . " a.malopmn=b.malopmn and a.matruongmn='" . $matruong_safe . "' order by a.ngaydexuat desc limit 0,200";
            else
                $sql4 = "SELECT  a.*,b.khoilop, b.tenlopmn FROM dexuatgiaotrinh a , lopmn b where a.malopmn=b.malopmn and a.matruongmn='" . $matruong_safe . "' order by a.ngaydexuat desc limit 0,200";

            $result4 = mysqli_query($link, $sql4);
            $tongrec4 = ($result4) ? mysqli_num_rows($result4) : 0;

            if ($tongrec4 > 0) {
                while ($row4 = mysqli_fetch_array($result4)) {
            ?>
                    <tr>
                        <td align="center" class="dkta1">
                            <div align="center">
                                <font face="arial" size="2"><a href="#xemgt" onclick="xoadl(<?php echo $row4["madx"]; ?>, '<?php echo $row4["trangthai"]; ?>')">Delete</a></font>
                            </div>
                        </td>
                        <td align="center" class="dkta1"><div align="center"><font face="arial" size="2"><?php echo $row4["madx"]; ?></font></div></td>
                        <td align="center" class="dkta1">
                            <div align="center"><font face="arial" size="2">
                                <?php
                                $date = date_create($row4["ngaydexuat"]);
                                echo date_format($date, 'd/m/Y H:i:s');
                                ?>
                            </font></div>
                        </td>
                        <td align="center" class="dkta1"><div align="center"><font face="arial" size="2"><?php echo $row4["tenlopmn"]; ?></font></div></td>
                        <td align="center" class="dkta1"><div align="center"><font face="arial" size="2"><?php echo $row4["soluongbe"]; ?></font></div></td>
                        <td align="center" class="dkta1"><div align="center"><font face="arial" size="2"><?php echo $row4["noidungdx"]; ?></font></div></td>
                        <td align="center" class="dkta1"><div align="center"><font face="arial" size="2"><?php echo $row4["nguoidx"]; ?></font></div></td>
                        <td align="center" class="dkta1"><div align="center"><strong><font face="arial" color="#990000" size="2"><?php echo $row4["trangthai"]; ?></font></strong></div></td>
                        <td align="center" class="dkta1"><div align="center"><font face="arial" size="2"><?php echo $row4["matruongmn"]; ?></font></div></td>
                    </tr>
            <?php
                }
            }
            ?>
        </table>
        <p align="center">&nbsp;</p>
    </form>
</body>
</HTML>

<script language="javascript">
    function checknum(e) {
        var a = e.keyCode ? e.keyCode : e.which;
        if (a < 48 || a > 57) {
            // Cho phép phím xóa, enter... (code cũ chặn hơi gắt nhưng mình giữ nguyên logic chỉ alert)
            alert("BAN CHI DUOC PHEP NHAP SO!");
            // document.f1.soluongbe.value = ""; // Logic này hơi gắt, user nhập sai 1 số xóa hết, bạn có thể comment lại
            return false;
        }
        return true;
    }

    function kt() {
        if (document.f1.khoilop.value == "") {
            alert("BAN CHUA CHON LOP!");
            return false;
        }
        if (document.f1.soluongbe.value == "") {
            alert("BAN CHUA NHAP SO LUONG BE!");
            return false;
        }
        if (document.f1.nguoidx.value == "") {
            alert("BAN CHUA NHAP TEN NGUOI DE XUAT!");
            return false;
        }

        if (confirm("Ban co dong y de xuat cac giao trinh nay khong?")) {
            // Lưu ý: Đảm bảo file xử lý tên là capnhatgiaotrinhdxnew.php như trong code cũ của bạn
            document.f1.action = "capnhatgiaotrinhdxnew.php"; 
            document.f1.submit();
        }
    }

    function chuyenlop() {
        document.f1.action = "dexuatgiaotrinhnew.php";
        document.f1.submit();
    }

    function xoadl(a, b) {
        if (b != "DX") {
            alert("Giao trinh nay da phat ban khong duoc xoa!");
            return false;
        }
        if (confirm("Ban co dong y xoa khong?")) {
            window.location.href = "dexuatgiaotrinhnew.php?kieu=D&madx=" + a;
        }
    }
</script>