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

include_once '../dbconn.php';

if (isset($_POST["save"])) {

    $id = $_POST['id'];
    $enrollment_serial_no = $_POST['enrollment_serial_no'];
    $current_date = date("Y-m-d H:i:s");


// Check if a file was uploaded without errors
    if (isset($_FILES["newImage"]) && $_FILES["newImage"]["error"] == 0) {
        $newFileName = '';

        // Get file details
        $fileName = $_FILES["newImage"]["name"];
        $fileTmpName = $_FILES["newImage"]["tmp_name"];
        $fileSize = $_FILES["newImage"]["size"];
        $fileError = $_FILES["newImage"]["error"];
        $fileType = $_FILES["newImage"]["type"];

        // Extract file extension
        $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
        // Generate a unique filename
        $unique_id = uniqid();
        $newFileName = $unique_id.  $enrollment_serial_no . "." . $fileExtension;
         $newpassport = 'https://healthassur.com/enrollment/uploads/'. $unique_id.  $enrollment_serial_no . "." . $fileExtension;

        // Destination path to save the uploaded file
        $uploadPath = "../../uploads/" . $newFileName;

        // Move the uploaded file to the destination directory
        if (move_uploaded_file($fileTmpName, $uploadPath)) {
            
           
            //SQL query to update the database with the new image name
            $sql = "UPDATE web_app_enrollee_data  
                SET Passport_link = '$newpassport',
                newchanges = 'yes',
                changedate = '$current_date'
            
            WHERE id = '$id'";

            if ($conn->query($sql) === TRUE) {
                 header("Location:../edit.php?id=$id saved");
                    exit();
            } else {
                echo "Error updating record: " . $conn->error;
            }

        } else {
            echo "Error uploading file!";
        }
    } else {
        echo "No file uploaded or error uploading file!";
    }
// SQL query to update data in the database
// $sql = "UPDATE web_app_enrollee_data 
//         SET 
//             passport_link = '$passport_path'
            
//         WHERE id = '$id'";

// // Execute the query
// if ($conn->query($sql) === TRUE) {
//     echo "Record updated successfully";
// } else {
//     echo "Error updating record: " . $conn->error;
// }
}
// Close connection
$conn->close();
?>
