<?php

include 'dbclass/dbclass.php';
// Establish connection to the database
$con = new mysqli('localhost', 'gdhhsxmy_moonniyurjalanidhislec', 'moonniyurjalanidhislec', 'gdhhsxmy_moonniyurjalanidhislec');

// 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 = 1;
$ward       = strtoupper($_POST['ward']);
$cnsno      = strtoupper($_POST['cnsno']);

// 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://moonniyurjalanidhislec.biz/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,cnsno) VALUES ('$regnumber', '$name', '$exam', '$fathername', '$number', '$address', '$panchayath', '$ward', '$imageFile', '$marklistPath','$cnsno')";

// Execute the SQL query
if ($con->query($sql) == true) {
    $inserted_id = $con->insert_id;

    $message        = 'Registered Successfully';
    $encodedMessage = urlencode($message);
    $url            = "https://moonniyurjalanidhislec.biz/index.php?message={$encodedMessage}";
    echo "<script>window.location.href='{$url}';</script>";
    exit();
} 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
