<?php

include_once './data/dbconn.php';


// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
   // Get the last enrollment serial number from the database
    $query = "SELECT (`enrollment_serial_no`) FROM (`web_app_enrollee_data`) ORDER BY id DESC LIMIT 1";

    $result = $conn->query($query);

    if ($result && $result->num_rows > 0) {
        $lastEnrollmentSerial = $result->fetch_assoc()['enrollment_serial_no'];
        // Increment the last enrollment serial number by 1
        $enrollmentSerialno = $lastEnrollmentSerial + 1;
    } else {
        // If there are no records in the database, start with a default value
        $enrollmentSerialno = 1000;
    }
    // File upload handling
    $targetDir = "uploads/"; // Directory where files will be uploaded
    $imageFileType = strtolower(pathinfo($_FILES["q99_passport"]["name"], PATHINFO_EXTENSION));
    $hmoId = $_POST['q110_hmoId'] . $enrollmentSerialno; // Assuming q110_hmoId contains the HMO ID

    // Set the target file name to HMO ID + enrollment serial number + extension
    $targetFile = $targetDir .$enrollmentSerialno . '.' . $imageFileType;

    $uploadOk = 1;

    // Check file size
    if ($_FILES["q99_passport"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

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

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["q99_passport"]["tmp_name"], $targetFile)) {
            // echo "The file " . basename($_FILES["q99_passport"]["name"]) . " has been uploaded.";
            
            
    $companyName = $_POST['q98_companyName'];
    $surname = $_POST['q4_surname'];
    $firstName = $_POST['q26_firstName'];
    $middleName = $_POST['q27_middleName'];
    $gender = $_POST['q22_gender'];
    $phoneNumber = $_POST['q23_phoneNumber23'];
    $emailAddress = $_POST['q24_emailAddress'];
    $dateOfBirth = $_POST['q9_dateOf']['day'] . '/' . $_POST['q9_dateOf']['month'] . '/' . $_POST['q9_dateOf']['year'];
    $groupOfPlan = $_POST['q106_groupOf'];
    $typeOfPlan = $_POST['q30_typeOf30'];
    $streetAddress = $_POST['q20_address']['addr_line1'];
    $streetAddress2 = $_POST['q20_address']['addr_line2'];
    $city = $_POST['q20_address']['city'];
    $state = $_POST['q20_address']['state'];
    $lga = $_POST['q20_address']['postal'];
    $employeeId = $_POST['q29_employeeId'];
    $hospitals = $_POST['q31_hospitals'];
    $genotype = $_POST['q_genotype'];
    $bloodGroup = $_POST['q_bloodgroup'];
    $allergies = $_POST['q_allergies'];
    $haspreexistingcondition = $_POST['q_Preextcon'];
    $preexistingcondition = $_POST['q_Preextconans'];
    $hassurgicalhistory = $_POST['q_surgicalque'];
    $surgicalHistory = $_POST['q_surgical'];
    $fileLink = 'https://visuretech.com/enrollment/'.$targetFile;

    // Insert new company data into the database, including file link
    $m_errs = "INSERT INTO `web_app_enrollee_data` ( `id` , `enrollment_serial_no`, `company_name` , `surname`, `first_name`, `middle_name`, `gender` , `phone_number` ,
    `email_address`, `date_of_birth`, `group_of_plan`, `type_of_plan` , `hmo_id`, `address_street` , `address_city`, `address_state`, `lga`, `employee_id` , `hospitals` ,
    `genotype`, `blood_group`, `allergies`, `has_pre_existing_condition`, `pre_existing_condition`, `has_surgical_history`, `surgical_history`, `Passport_link` ) 
    VALUES ( NULL , '$enrollmentSerialno', '$companyName', '$surname', '$firstName', '$middleName', '$gender', '$phoneNumber', '$emailAddress', '$dateOfBirth', '$groupOfPlan',
    '$typeOfPlan', '$hmoId', '$streetAddress', '$city', '$state', '$lga', '$employeeId', '$hospitals', '$genotype', '$bloodGroup', '$allergies', '$haspreexistingcondition',
    '$preexistingcondition', '$hassurgicalhistory', '$surgicalHistory', '$fileLink')";
    
    $conn->query($m_errs);
   
    
    //Spouse
    
    $spousesSurname = $_POST['q36_spousesSurname'];
    
    if (!$spousesSurname == ''){
        
        
        $q37_spousesFirst = $_POST['q37_spousesFirst'];
        $q38_spousesMiddle = $_POST['q38_spousesMiddle'];
        // $q41_spousesPhone = $_POST['q41_spousesPhone[full]'];
        $q41_spousesPhone = '0000000000';
        $spousedateOfBirth = $_POST['q42_spousesDate']['day'] . '/' . $_POST['q42_spousesDate']['month'] . '/' . $_POST['q42_spousesDate']['year'];
        
        $q87_spousesGender = $_POST['q87_spousesGender'];
        $q111_spousesHmo = $_POST['q111_spousesHmo'];
        $q58_spousesHospitals = $_POST['q58_spousesHospitals'];
        
        // Get the last enrollment serial number from the database
        $query = "SELECT (`enrollment_serial_no`) FROM (`web_app_enrollee_data`) ORDER BY id DESC LIMIT 1";
    
        $result = $conn->query($query);
    
        if ($result && $result->num_rows > 0) {
            $lastEnrollmentSerial = $result->fetch_assoc()['enrollment_serial_no'];
            // Increment the last enrollment serial number by 1
            $enrollmentSerialno = $lastEnrollmentSerial + 1;
        } else {
            // If there are no records in the database, start with a default value
            $enrollmentSerialno = 1000;
        }
        // File upload handling
        $targetDir = "uploads/"; // Directory where files will be uploaded
        $imageFileType = strtolower(pathinfo($_FILES["q100_spousesPassport"]["name"], PATHINFO_EXTENSION));
        $hmoId = $_POST['q110_hmoId'] . $enrollmentSerialno . '/B'; // Assuming q110_hmoId contains the HMO ID
    
        // Set the target file name to HMO ID + enrollment serial number + extension
        $targetFile = $targetDir .$enrollmentSerialno . '.' . $imageFileType;
        
        $spousefileLink = 'https://visuretech.com/enrollment/'.$targetFile;
    
        $uploadOk = 1;
    
        // Check file size
        if ($_FILES["q100_spousesPassport"]["size"] > 500000) {
            echo "Sorry, your file is too large.";
            $uploadOk = 0;
        }
    
        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            echo "Sorry, your file was not uploaded.";
        // if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES["q100_spousesPassport"]["tmp_name"], $targetFile)) {
        
            $spousedata = "INSERT INTO `web_app_enrollee_data` ( `id` , `enrollment_serial_no`, `company_name` , `surname`, `first_name`, `middle_name`, `gender` , `phone_number` ,
        `email_address`, `date_of_birth`, `hmo_id`, `hospitals` , `Passport_link` ) 
        VALUES ( NULL , '$enrollmentSerialno', '$companyName', '$spousesSurname', '$q37_spousesFirst', '$q38_spousesMiddle', '$q87_spousesGender', '$q41_spousesPhone', '$emailAddress', 
        '$spousedateOfBirth', '$hmoId', '$q58_spousesHospitals', '$spousefileLink')";
        
            }
            
            $conn->query($spousedata);
            
    }
    
    //1st Dependant
    $q50_1stDependents = $_POST['q50_1stDependents'];
    
    if (!$q50_1stDependents == ''){
          $q51_1stDependents51 = $_POST['q51_1stDependents51'];
        $q52_1stDependents52 = $_POST['q52_1stDependents52'];
        // $q54_1stDependents54 = $_POST['q54_1stDependents54'];
          $q54_1stDependents54 = '0000000000';
        $q55_1stDependents55 = $_POST['q55_1stDependents55']['day'] . '/' . $_POST['q55_1stDependents55']['month'] . '/' . $_POST['q55_1stDependents55']['year'];
        
        $q89_1stDependents89 = $_POST['q89_1stDependents89'];
        $q112_1stDependents112 = $_POST['q112_1stDependents112'];
        $q90_1stDependents90 = $_POST['q90_1stDependents90'];
        
        // Get the last enrollment serial number from the database
        $query = "SELECT (`enrollment_serial_no`) FROM (`web_app_enrollee_data`) ORDER BY id DESC LIMIT 1";
    
        $result = $conn->query($query);
    
        if ($result && $result->num_rows > 0) {
            $lastEnrollmentSerial = $result->fetch_assoc()['enrollment_serial_no'];
            // Increment the last enrollment serial number by 1
            $enrollmentSerialno = $lastEnrollmentSerial + 1;
        } else {
            // If there are no records in the database, start with a default value
            $enrollmentSerialno = 1000;
        }
        // File upload handling
        $targetDir = "uploads/"; // Directory where files will be uploaded
        $imageFileType = strtolower(pathinfo($_FILES["q101_1stDependents101"]["name"], PATHINFO_EXTENSION));
        $hmoId = $_POST['q110_hmoId'] . $enrollmentSerialno . '/C';; // Assuming q110_hmoId contains the HMO ID
    
        // Set the target file name to HMO ID + enrollment serial number + extension
        $targetFile = $targetDir .$enrollmentSerialno . '.' . $imageFileType;
        
        $spousefileLink = 'https://visuretech.com/enrollment/'.$targetFile;
    
        $uploadOk = 1;
    
        // Check file size
        if ($_FILES["q101_1stDependents101"]["size"] > 500000) {
            echo "Sorry, your file is too large.";
            $uploadOk = 0;
        }
    
        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            echo "Sorry, your file was not uploaded.";
        // if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES["q101_1stDependents101"]["tmp_name"], $targetFile)) {
        
            $firstdepdata = "INSERT INTO `web_app_enrollee_data` ( `id` , `enrollment_serial_no`, `company_name` , `surname`, `first_name`, `middle_name`, `gender` , `phone_number` ,
        `email_address`, `date_of_birth`, `hmo_id`, `hospitals` , `Passport_link` ) 
        VALUES ( NULL , '$enrollmentSerialno', '$companyName', '$q50_1stDependents', '$q51_1stDependents51', '$q52_1stDependents52', '$q87_spousesGender', '$q54_1stDependents54', '$emailAddress', 
        '$q55_1stDependents55', '$hmoId', '$q90_1stDependents90', '$spousefileLink')";
        
            }
            
            $conn->query($firstdepdata);
    }
    
    
    //2nd Dependant
   
        // Redirect to an external link
        header("Location: ./success.html");
        exit(); 
        // Make sure no other output is sent
   
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
        }
        
    }

}