<?php
$date = date('d/M/Y');
$serial_date = date('Ymd');
$select = "--select--";

if (isset($_POST['upload_pin_btn'])) {
    $pin_total = 10;
    $success = true;

    for ($i = 1; $i <= $pin_total; $i++) {
        $gen_pin = inject_checker($connection, $_POST["gen_pin{$i}"]);
        $pin_upload_term = inject_checker($connection, $_POST['pin_upload_term']);

        if (empty($gen_pin)) {
            $_SESSION['msg'] = "❌ Please generate pins before uploading.";
            $_SESSION['type'] = "warning";
            header("Location: generate_pins");
            exit();
        }

        if ($pin_upload_term === $select) {
            $_SESSION['msg'] = "❌ Please select the term where the generated pin will be used.";
            $_SESSION['type'] = "warning";
            header("Location: generate_pins");
            exit();
        }

        $term_table = "";
        $term_column = "";

        switch (strtolower($pin_upload_term)) {
            case "first term":
                $term_table = "pin1";
                $term_column = "first_term_pin";
                break;
            case "second term":
                $term_table = "pin2";
                $term_column = "second_term_pin";
                break;
            case "third term":
                $term_table = "pin3";
                $term_column = "third_term_pin";
                break;
            default:
                $_SESSION['msg'] = "❌ Invalid term selected.";
                $_SESSION['type'] = "error";
                header("Location: generate_pins");
                exit();
        }

        // Check for duplicate pin
        $check_stmt = $connection->prepare("SELECT id FROM `$term_table` WHERE `$term_column` = ?");
        $check_stmt->bind_param("s", $gen_pin);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();

        if ($check_result->num_rows > 0) {
            $_SESSION['msg'] = "❌ Pin {$gen_pin} already exists.";
            $_SESSION['type'] = "warning";
            $check_stmt->close();
            continue;
        }
        $check_stmt->close();

        // Get current count for serial number
        $count_result = $connection->query("SELECT COUNT(*) AS total FROM `$term_table`");
        $row = $count_result->fetch_assoc();
        $serial_number = $serial_date . $row['total'];

        // Insert into pin table
        $insert_stmt = $connection->prepare("INSERT INTO `$term_table`(`term`, `$term_column`, `serial_number`, `upload_date`) VALUES (?, ?, ?, ?)");
        $insert_stmt->bind_param("ssss", $pin_upload_term, $gen_pin, $serial_number, $date);
        if (!$insert_stmt->execute()) {
            $success = false;
        }
        $insert_stmt->close();

        // Insert into unused_pins
        $unused_stmt = $connection->prepare("INSERT INTO `unused_pins`(`term`, `unused_pins`, `serial_number`, `upload_date`) VALUES (?, ?, ?, ?)");
        $unused_stmt->bind_param("ssss", $pin_upload_term, $gen_pin, $serial_number, $date);
        if (!$unused_stmt->execute()) {
            $success = false;
        }
        $unused_stmt->close();
    }

    if ($success) {
        $_SESSION['msg'] = "Pin upload successful.";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Some pins failed to upload. Check for duplicates or database issues.";
        $_SESSION['type'] = "error";
    }

    header("Location: generate_pins");
    exit();
}
?>
<?php
$pin_total = 10; // Number of pins to display
?>

<div class='page-title'>
    <div>
        <h1><i class='fa fa-laptop'></i> Result Pin Management</h1>
        <p>Generate Result Pins</p>
    </div>
</div>

<div class='card'>
    <div class='panel panel-primary'>
        <div class='panel-heading'>
            <h4 class='text-center'>Generate Result Pins</h4>
        </div>
        <div class='panel-body'>
            <form method='POST' action=''>
                <div class='row'>
                    <div class='col-md-6'>
                    <div class='input-group mb-3'>
                            <span class='input-group-addon'>TERM</span>
                            <select class='form-control' name='pin_upload_term' required>
                                <option selected disabled>--select--</option>
                                <?php
                                    $terms = ["First Term", "Second Term", "Third Term"];
                                    foreach ($terms as $term) {
                                        echo "<option value='{$term}'>{$term}</option>";
                                    }
                                ?>
                            </select>
                        </div>
                        <br />
                        <?php for ($i = 1; $i <= $pin_total; $i++): ?>                                                 
                            <div class='input-group mb-3'>
                                <span class='input-group-addon'>PIN <?php echo $i; ?>:</span>
                                <input 
                                    type='text' 
                                    name='gen_pin<?php echo $i; ?>' 
                                    value='<?php echo rnd(10, false, false, true); ?>' 
                                    required 
                                    class='form-control' 
                                />
                            </div>
                        <?php endfor; ?>

                       

                        <input 
                            type='submit' 
                            name='upload_pin_btn' 
                            value='Upload Pins' 
                            class='btn btn-success btn-block' 
                        />
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>


