<?php
session_start();

// Check if the user is logged in by verifying the session variable
if (!isset($_SESSION['school_name']) || !isset($_SESSION['emis_code'])) {
    // Redirect to login page if the session is not set
    header("Location: login.php");
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve the session variables
$school_name = $_SESSION['school_name'];
$emis_code = $_SESSION['emis_code'];
$cate_id = $_SESSION['cate_id'] ;        // Store school Category in session
$level_id = $_SESSION['level_id'];      // Store school Level in session

// Include the database configuration file
include 'connect.php';

// Function to resize the image
function resizeImage($filePath, $newWidth, $newHeight, $maxSize, $newFilePath) {
    if (getimagesize($filePath)) {
        $info = getimagesize($filePath);
        $width = $info[0];
        $height = $info[1];
        $mime = $info['mime'];

        // Create a new image resource
        switch ($mime) {
            case 'image/jpeg':
                $image = imagecreatefromjpeg($filePath);
                break;
            case 'image/png':
                $image = imagecreatefrompng($filePath);
                break;
            case 'image/gif':
                $image = imagecreatefromgif($filePath);
                break;
            default:
                throw new Exception('Unsupported image type.');
        }

        // Create a new image with the new size
        $resizedImage = imagecreatetruecolor($newWidth, $newHeight);

        // Preserve transparency for PNG and GIF
        if ($mime == 'image/png' || $mime == 'image/gif') {
            imagecolortransparent($resizedImage, imagecolorallocatealpha($resizedImage, 0, 0, 0, 127));
            imagealphablending($resizedImage, false);
            imagesavealpha($resizedImage, true);
        }

        // Resize the image
        imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

        // Save the resized image as JPG
        imagejpeg($resizedImage, $newFilePath, 100); // Highest quality (0-100)

        // Check if the file size is within the limit
        if (filesize($newFilePath) > $maxSize) {
            throw new Exception('Image exceeds the maximum file size.');
        }

        // Clean up
        imagedestroy($image);
        imagedestroy($resizedImage);

        return $newFilePath;
    } else {
        throw new Exception('Invalid image file.');
    }
}

// Process the form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve POST data and validate
    $stname = $_POST['stname'];
    $stfname = $_POST['stfname'];
    $stge = $_POST['stge'];
    $stbirthday = $_POST['stbirthday'];
    $stbfno = $_POST['stbfno'];
    $strel = $_POST['strel'];
    $stmobno = $_POST['stmobno'];
    $classadm = $_POST['classadm'];
    $doadm = $_POST['doadm'];
    $admno = $_POST['admno'];
    $stclass = $_POST['stclass'];
    $stcsec = $_POST['stcsec'];
    $stcno = $_POST['stcno'];
    $stgroup = isset($_POST['stgroup']) ? $_POST['stgroup'] : ''; // Retrieve 'stgroup' safely
    $stvillage = $_POST['stvillage'];
    $stpo = $_POST['stpo'];
    $district = $_POST['districts_dropdown'];
    $tehsil = $_POST['tehsil_dropdown'];
    $constituency = $_POST['constituency_dropdown'];
    $union_council = $_POST['union_councils_dropdown'];

	// Validate Form B No. and Parent's Mobile No.
    if (strlen($stbfno) !== 13) {
        echo "<script>
                alert('CNIC / Form B No. must be exactly 13 digits.');
                window.location.href = 'student_profile.php'; // Redirect to the same page
              </script>";
        exit;
    }

    if (!preg_match('/^\d{11}$/', $stmobno)) {
        echo "<script>
                alert('Mobile No. must be exactly 11 digits.');
                window.location.href = 'student_profile.php'; // Redirect to the same page
              </script>";
        exit;
    }
	
    // Check if Form B No. is unique
    $sqlCheck = $conn->prepare("SELECT COUNT(*) FROM student_information WHERE stbfno = ?");
    $sqlCheck->bind_param("s", $stbfno);
    $sqlCheck->execute();
    $sqlCheck->bind_result($count);
    $sqlCheck->fetch();
    $sqlCheck->close();

    if ($count > 0) {
        die("Form B No. is already registered.");
    }

    // File upload handling for student picture
    $targetDir = "uploads/students/";
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    $stpic = $_FILES["stpic"]["name"];
    $targetFilePath = $targetDir . basename($stpic);

    if (move_uploaded_file($_FILES["stpic"]["tmp_name"], $targetFilePath)) {
        // Resize the image to 3 inches (288 pixels) height and 2 inches (192 pixels) width
        $newFileName = $stbfno . '.jpg';
        $newFilePath = $targetDir . $newFileName;

        try {
            $resizedImagePath = resizeImage($targetFilePath, 192, 288, 500000, $newFilePath); // 500 KB max size

            // Delete the original image
            unlink($targetFilePath);

            // Insert Student Information into the database
            $sqlStudentInfo = $conn->prepare("INSERT INTO student_information (emis_code, cate_id, level_id, stname, stfname, stge, stbirthday, stbfno, strel, stmobno, classadm, doadm, admno, stpic, stclass, stcsec, stcno, stgroup, stvillage, stpo, district_id, tehsil_id, uc_id, cons_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $sqlStudentInfo->bind_param("ssssssssssssssssssssssss", $emis_code, $cate_id, $level_id, $stname, $stfname, $stge, $stbirthday, $stbfno, $strel, $stmobno, $classadm, $doadm, $admno, $newFileName, $stclass, $stcsec, $stcno, $stgroup, $stvillage, $stpo, $district, $tehsil, $union_council, $constituency);

            if ($sqlStudentInfo->execute()) {
                echo "<script>
                        alert('Record inserted successfully');
                        window.location.href = 'student_profile.php'; // Redirect to student_profile.php
                      </script>";
            } else {
                echo "<script>
                        alert('Error: " . $sqlStudentInfo->error . "');
                        window.location.href = 'student_profile.php'; // Redirect to student_profile.php
                      </script>";
            }

            $sqlStudentInfo->close();
        } catch (Exception $e) {
            echo "<script>
                    alert('Error: " . $e->getMessage() . "');
                    window.location.href = 'student_profile.php'; // Redirect to student_profile.php
                  </script>";
        }
    } else {
        echo "<script>
                alert('Error uploading the file.');
                window.location.href = 'student_profile.php'; // Redirect to student_profile.php
              </script>";
    }

    // Close connection
    $conn->close();
}
}
?>
