<?php
// Database connection
// Connect to MySQL

include_once '../dbconn.php';



// $conn = mysqli_connect("localhost", "vinkblgn_regportal", "Victor@007", "vinkblgn_regportal");

// Check connection
// if (!$conn) {
//     die("Connection failed: " . mysqli_connect_error());
// }

if (isset($_POST["add"])) {
// Collect form data
$group = $_POST['group'];
$firstName = $_POST['firstname'];
$middleName = $_POST['middlename'];
$lastName = $_POST['lastname'];
$phoneNumber = $_POST['phonenumber'];
$email = $_POST['email'];
$employeeID = $_POST['employeeid'];
$gender = $_POST['gender'];
$dateOfBirth = $_POST['dob'];
$state = $_POST['state'];
$lga = $_POST['lga'];
$city = $_POST['city'];
$address = $_POST['address'];
$planType = $_POST['plantype'];
$groupType = $_POST['grouptype'];
$selectedProvider = $_POST['provider'];
$status = $_POST['status'];
$genotype = $_POST['genotype'];
$bloodgroup = $_POST['bloodgroup'];
$allergies = $_POST['allergies'];
$haspreexisting = $_POST['haspreexisting'];
$preexisting = $_POST['preexisting'];
$hassurgicalhist = $_POST['hassurgicalhist'];
$surgicalhist = $_POST['surgicalhist'];

// $company_code = $_POST['company_code'];
// $enrollment_serial_no = '11';
// $hmo_id = '0000';

// SQL query
$sql = "SELECT company_code FROM web_app_enrollment_form WHERE company = '$group'";

// Execute query
$resultcode = $conn->query($sql);

// Check if there is a result
if ($resultcode->num_rows > 0) {
    // Output data of each row
    while($rowcode = $resultcode->fetch_assoc()) {
        // Save company code as $companycode variable
        $company_code = $rowcode["company_code"];
    }
} else {
    echo "Company not found.";
}
$principal_id = NULL;


// 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
    $enrollment_serial_no = $lastEnrollmentSerial + 1;
} else {
    // If there are no records in the database, start with a default value
    $enrollment_serial_no = 1000;
}
$hmo_id= 'HA/'. $company_code .'/'. $enrollment_serial_no;



// File upload
$targetDir = "../../uploads/";
$target = "/uploads/";
$imageFileType = strtolower(pathinfo($_FILES["passport"]["name"], PATHINFO_EXTENSION));

 // Set the target file name to HMO ID + enrollment serial number + extension
$targetFile = $targetDir .$enrollment_serial_no . '.' . $imageFileType;
$uploadOk = 1;
    // Check file size
    if ($_FILES["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["passport"]["tmp_name"], $targetFile)) {
            // echo "The file " . basename($_FILES["passport"]["name"]) . " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }

    $passport_path =  'https://healthassur.com/enrollment'.$target .$enrollment_serial_no . '.' . $imageFileType;

// $passport = $_FILES['passport']['name'];
// $passport_tmp = $_FILES['passport']['tmp_name'];
// $passport_path = "passports/" . $passport; // You can adjust the path as needed

// // Move uploaded file to desired location
// move_uploaded_file($passport_tmp, $passport_path);

// insert data into database
$sql = "INSERT INTO web_app_enrollee_data (enrollment_serial_no, hmo_id, principal_id, company_name, first_name, middle_name, surname, phone_number, email_address,employee_id, gender, date_of_birth, type_of_plan, group_of_plan, address_state, lga,address_city, address_street, hospitals, genotype, blood_group, allergies, has_pre_existing_condition, pre_existing_condition,has_surgical_history, surgical_history, status, Passport_Link)
VALUES ( '$enrollment_serial_no', '$hmo_id', '$principal_id', '$group', '$firstName', '$middleName', '$lastName', '$phoneNumber', '$email', '$employeeID', '$gender', '$dateOfBirth', '$planType', '$groupType', '$state','$lga','$city', '$address', '$selectedProvider', '$genotype', '$bloodgroup','$allergies','$haspreexisting','$preexisting','$hassurgicalhist','$surgicalhist','$status', '$passport_path')";

if ($conn->query($sql) === TRUE) {
    header("Location:../index.php?added");
    exit();
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
}
else {
    header("Location:../index.php?error");
    exit();
}



$conn->close();
?>