<?php

include_once './admin/dbconn.php';

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Get the last submission_id number from the database
    $query = "SELECT `submission_id` FROM `submissions` ORDER BY `id` DESC LIMIT 1";
    $result = $conn->query($query);

    if ($result && $result->num_rows > 0) {
        $lastsubmissionid = $result->fetch_assoc()['submission_id'];
        // Increment the last enrollment serial number by 1
        $submission_id = $lastsubmissionid + 1;
    } else {
        // If there are no records in the database, start with a default value
        $submission_id = 1;
    }
    
    $year = $_POST['q61_year'];
    $cmo_induction_status = $_POST['q16_cmoInduction'];
    $deanery_name = $_POST['q10_deaneryName'];


    // Get Deanary Code
    if ($deanery_name == 'Agege Deanery') {
        $denarycode = 'AGG';
    } else if ($deanery_name == 'Apapa Deanery') {
        $denarycode = 'APP';
    } else if ($deanery_name == 'Ajah Deanery') {
        $denarycode = 'AJH';
    } else if ($deanery_name == 'Badagry Deanery') {
        $denarycode = 'BGY';
    } else if ($deanery_name == 'Epe Deanery') {
        $denarycode = 'EPE';
    } else if ($deanery_name == 'Festac Deanery') {
        $denarycode = 'FTC';
    } else if ($deanery_name == 'Iba Deanery') {
        $denarycode = 'IBA';
    } else if ($deanery_name == 'Ijanikin Deanery') {
        $denarycode = 'IJK';
    } else if ($deanery_name == 'Ijede Deanery') {
        $denarycode = 'IJD';
    } else if ($deanery_name == 'Ikeja Deanery') {
        $denarycode = 'IKJ';
    } else if ($deanery_name == 'Ilemba Deanery') {
        $denarycode = 'LMB';
    } else if ($deanery_name == 'Ikorodu Deanery') {
        $denarycode = 'IKD';
    } else if ($deanery_name == 'Ipaja Deanery') {
        $denarycode = 'IPJ';
    } else if ($deanery_name == 'Isolo Deanery') {
        $denarycode = 'ISL';
    } else if ($deanery_name == 'Lagos Island Deanery') {
        $denarycode = 'LSD';
    } else if ($deanery_name == 'Lekki Deanery') {
        $denarycode = 'LKK';
    } else if ($deanery_name == 'Maryland Deanery') {
        $denarycode = 'MYD';
    } else if ($deanery_name == 'Satellite Deanery') {
        $denarycode = 'STL';
    } else if ($deanery_name == 'Surulere Deanery') {
        $denarycode = 'SLR';
    } else if ($deanery_name == 'Yaba Deanery') {
        $denarycode = 'YBA';
    }
    
   
    // Generate ID_number for registration
    if ($cmo_induction_status == "New Inductee") {
         // Idnumber generation CMO-denarycode/year-id
         
        $id_number ='CMO-' .$denarycode .'/'. $year . '-' .  $submission_id; 
        
    } else {
        $id_number = $_POST['q23_idNumber'];
        
    }

    // File upload handling
    $passportDir = "uploads/"; // Directory where files will be uploaded
    $passportFileType = strtolower(pathinfo($_FILES["q17_passportUpload"]["name"], PATHINFO_EXTENSION));
    $passportFile = $passportDir . 'passport-' . $submission_id . '.' . $passportFileType;
    $passportOk = 1;

    // Check passport size
    if ($_FILES["q17_passportUpload"]["size"] > 10485760) {
        echo "Sorry, your passport is too large.";
        $passportOk = 0;
    }

    // Allow only certain file formats
    if ($passportFileType != "jpg" && $passportFileType != "png" && $passportFileType != "jpeg" && $passportFileType != "gif") {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $passportOk = 0;
    }

    // Check if $passportOk is set to 0 by an error
    if ($passportOk == 0) {
        echo "Sorry, your passport was not uploaded.";
    } else {
        if (move_uploaded_file($_FILES["q17_passportUpload"]["tmp_name"], $passportFile)) {

            // Signature upload handling
            $signatureFile = '';
            if (!empty($_FILES["q36_signatureUpload"]["name"])) {
                $signatureDir = "uploads/"; // Directory where files will be uploaded
                $signatureFileType = strtolower(pathinfo($_FILES["q36_signatureUpload"]["name"], PATHINFO_EXTENSION));
                $signatureFile = $signatureDir . 'signature-' . $submission_id . '.' . $signatureFileType;
                $signatureOk = 1;

                // Check signature size
                if ($_FILES["q36_signatureUpload"]["size"] > 10485760) {
                    echo "Sorry, your signature is too large.";
                    $signatureOk = 0;
                }

                // Allow only certain file formats
                if ($signatureFileType != "jpg" && $signatureFileType != "png" && $signatureFileType != "jpeg" && $signatureFileType != "gif") {
                    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for your signature upload.";
                    $signatureOk = 0;
                }

                // Check if $signatureOk is set to 0 by an error
                if ($signatureOk == 0) {
                    echo "Sorry, your signature was not uploaded.";
                } else {
                    if (!move_uploaded_file($_FILES["q36_signatureUpload"]["tmp_name"], $signatureFile)) {
                        echo "Sorry, there was an error uploading your Signature.";
                    }
                }
            }
            
            
            // marriage upload handling
            $marriageFile = '';
            if (!empty($_FILES["q60_churchMarriage"]["name"])) {
                $marriageDir = "uploads/"; // Directory where files will be uploaded
                $marriageFileType = strtolower(pathinfo($_FILES["q60_churchMarriage"]["name"], PATHINFO_EXTENSION));
                $marriageFile = $marriageDir . 'marriage-' . $submission_id . '.' . $marriageFileType;
                $marriageOk = 1;

                // Check marriage size
                if ($_FILES["q60_churchMarriage"]["size"] > 10485760) {
                    echo "Sorry, your marriage is too large.";
                    $marriageOk = 0;
                }

                // Allow only certain file formats
                if ($marriageFileType != "jpg" && $marriageFileType != "png" && $marriageFileType != "jpeg" && $marriageFileType != "gif") {
                    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for your marriage upload.";
                    $marriageOk = 0;
                }

                // Check if $marriageOk is set to 0 by an error
                if ($marriageOk == 0) {
                    echo "Sorry, your marriage was not uploaded.";
                } else {
                    if (!move_uploaded_file($_FILES["q60_churchMarriage"]["tmp_name"], $marriageFile)) {
                        echo "Sorry, there was an error uploading your marriage.";
                    }
                }
            }

            // Collect form data
            $year = $_POST['q61_year'];
            $title = $_POST['q4_title'];
            $last_name = $_POST['q5_surname'];
            $middle_name = $_POST['q6_middleName'];
            $first_name = $_POST['q7_firstName'];
            $fullname = $_POST['q5_surname'] . ' ' . $_POST['q6_middleName'] . ' ' . $_POST['q7_firstName'];
            $phone = $_POST['q8_phone'];
            $email = $_POST['q9_email'];
            $parish_name = $_POST['q13_typeA13'];
            $cmo_induction_status = $_POST['q16_cmoInduction'];
            $blood_group = $_POST['q18_bloodGroup'];
            $do_you_require_a_mattress_to_sleep_over = $_POST['q46_doYou46'];
            $do_you_require_a_hotel_accommodation = $_POST['q53_doYou53'];
            $if_yes_click_a_range = $_POST['q54_ifYes'];
            $how_long_have_you_been_canonically_married = $_POST['q54_ifYes'];
            $passport_link = 'https://visuretech.com/lacmon/'.$passportFile;
            $signature_link = 'https://visuretech.com/lacmon/'.$signatureFile;
            $Marriage_certificate_link = 'https://visuretech.com/lacmon/'.$marriageFile;
            
            // Insert new company data into the database, including file link
            $m_errs = "INSERT INTO `submissions` ( `id` , `submission_id`, `year`, `title` , `last_name`, `middle_name`, `first_name`, `fullname` , `phone` ,
            `email`, `deanery_name`, `parish_name`, `cmo_induction_status` , `id_number`, `blood_group` , `do_you_require_a_mattress_to_sleep_over`, `do_you_require_a_hotel_accommodation`, `if_yes_click_a_range`, `how_long_have_you_been_canonically_married`, `passport_link` , `signature_link` ,
            `Marriage_certificate_link` ) 
            VALUES ( NULL , '$submission_id', '$year', '$title', '$last_name', '$middle_name', '$first_name', '$fullname', '$phone', '$email', '$deanery_name', '$parish_name',
            '$cmo_induction_status', '$id_number', '$blood_group', '$do_you_require_a_mattress_to_sleep_over', '$do_you_require_a_hotel_accommodation', '$if_yes_click_a_range', '$how_long_have_you_been_canonically_married', '$passport_link', '$signature_link', '$Marriage_certificate_link')";
        
            $conn->query($m_errs);

            header("Location: ./success.html");
            exit();
        } else {
            echo "Sorry, there was an error uploading your Passport.";
        }
    }
}
?>
