<?php
include 'dbclass/dbclass.php';
// Establish connection to the database
$con = new mysqli('localhost', 'gdhhsxmy_kpamajeedmla', 'kpamajeedmla', 'gdhhsxmy_kpamajeedmla');

// Check connection
if ($con->connect_error) {
    die('Connection failed: ' . $con->connect_error);
}

// Get form data
// Get form data and convert to uppercase
$regnumber  = strtoupper($_POST['regnumber']);
$name       = strtoupper($_POST['name']);
$exam       = strtoupper($_POST['exam']);
$fathername = strtoupper($_POST['fathername']);
$number     = strtoupper($_POST['number']);
$address    = strtoupper($_POST['address']);
$panchayath = strtoupper($_POST['panchayath']);
$ward       = strtoupper($_POST['ward']);

// Handle cropped image
$imageFile = null;

if (!($_POST['croppedImage'])) {
    $url = 'index.php?message=Unsupported+file+format';
    echo "<script>window.location.href='{$url}';</script>";
    exit();
}

if (isset($_POST['croppedImage'])) {
    $folderPath   = 'uploads/';
    $image_parts  = explode(';base64,', $_POST['croppedImage']);
    $image_base64 = base64_decode($image_parts[1]);
    $imageFile    = $folderPath . uniqid() . '.png';
    file_put_contents($imageFile, $image_base64);
}

// Check file formats and upload mark list
$marklistPath = uploadFile('marklist', 'uploads/', ['pdf', 'jpg', 'jpeg', 'png']);

if (!$imageFile || !$marklistPath) {
    $url = 'index.php?message=Unsupported+file+format';
    echo "<script>window.location.href='{$url}';</script>";
    exit();
}


$query  = "SELECT * FROM students WHERE regnumber='$regnumber'";
$result = $con->query($query);

for ($i = 0; $i < $result->num_rows; $i++) {
    $row = $result->fetch_assoc();

    if ($row['regnumber'] == $regnumber) {
        $message        = 'Already registered with this register number';
        $encodedMessage = urlencode($message);
        $url            = "https://kpamajeedmla.in/index.php?message={$encodedMessage}";
        echo "<script>window.location.href='{$url}';</script>";
        exit();
    }
}

// SQL query to insert data into the database
$sql = "INSERT INTO students (regnumber, name, exam, fathername, number, address, panchayath, ward, photo, marklist) VALUES ('$regnumber', '$name', '$exam', '$fathername', '$number', '$address', '$panchayath', '$ward', '$imageFile', '$marklistPath')";

// Execute the SQL query
if ($con->query($sql) == true) {
    $inserted_id = $con->insert_id;
    // echo "Success 🥳";
    ?>
    // Close the database connection
    // $con->close();

    // Redirect to ticket.php with the ID as a URL parameter
   <script>
   
        if (window.screen.width > 414) {
            window.location.href = 'ticket.php?id=<?php echo $inserted_id; ?>';
        } else {
            window.location.href = 'ticket-mobile.php?id=<?php echo $inserted_id; ?>';
        }
    </script>

    <!-- <button id="download-btn">Download</button> -->
    <!-- <script src="sweetalert.js"></script>

    <script>
        // SweetAlert to show success message
        swal({
            title: "Good job!",
            text: "New record created successfully",
            icon: "success"
        }).then(function() {
            // Redirect to index.php after SweetAlert is closed
            // window.location.href = "index.php";
        });
    </script> -->
<?php
} else {
    echo 'Error: ' . $sql . '<br>' . $con->error;
}

// Function to upload file with random name
function uploadFile($fileInputName, $targetDir, $allowedFormats)
{
    $fileType = pathinfo($_FILES[$fileInputName]['name'], PATHINFO_EXTENSION);

    if (!in_array(strtolower($fileType), $allowedFormats)) {
        return null;
    }
    $randomFileName = uniqid() . '_' . basename($_FILES[$fileInputName]['name']);
    $targetFile     = $targetDir . $randomFileName;

    // Move the uploaded file to the specified directory
    if (move_uploaded_file($_FILES[$fileInputName]['tmp_name'], $targetFile)) {
        return $targetFile;
    } else {
        return null;
    }
}

// Close database connection
?>