<?php
session_start();

if (!isset($_SESSION['inactive'])) {
    echo json_encode(['status' => 'error', 'message' => 'User session not found.']);
    exit();
}

$chap = $_SESSION['inactive'];
include "../../connect/db.php";

// Create a new MySQLi instance
$mysqli = new mysqli($host, $username, $password, $dbname);

// Check connection
if ($mysqli->connect_error) {
    echo json_encode(['status' => 'error', 'message' => 'Connection failed: ' . $mysqli->connect_error]);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Check if a file was uploaded
    if (isset($_FILES['fileToUpload'])) {
        $file = $_FILES['fileToUpload'];

        // Check if file upload was successful
        if ($file['error'] == UPLOAD_ERR_OK) {
            // Define allowed file extensions and max size
            $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
            $maxSizeMB = 5;
            $maxSizeBytes = $maxSizeMB * 1024 * 1024; // Convert MB to Bytes

            // Get file details
            $fileName = basename($file['name']);
            $fileTmpName = $file['tmp_name'];
            $fileSize = $file['size'];
            $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

            // Validate file extension
            if (!in_array($fileExtension, $allowedExtensions)) {
                echo json_encode(['status' => 'error', 'message' => 'Invalid file type. Allowed types are: ' . implode(', ', $allowedExtensions)]);
                exit();
            }

            // Validate file size
            if ($fileSize > $maxSizeBytes) {
                echo json_encode(['status' => 'error', 'message' => 'File size exceeds ' . $maxSizeMB . ' MB. Please select a smaller file.']);
                exit();
            }

            // Define upload directory and move the file
            $uploadDir = '../../uploads/' . $chap . '/';
            $img_path = 'uploads/' . $chap . '/' . $fileName; // Correct path for database

            // Create the upload directory if it does not exist
            if (!file_exists($uploadDir)) {
                if (!mkdir($uploadDir, 0755, true)) {
                    echo json_encode(['status' => 'error', 'message' => 'Failed to create upload directory.']);
                    exit();
                }
            }

            $uploadFile = $uploadDir . $fileName;

            if (move_uploaded_file($fileTmpName, $uploadFile)) {
                // Prepare an SQL statement for updating
                $stmt = $mysqli->prepare("UPDATE users SET img_path = ?, reg_step = ? WHERE email = ?");
                if ($stmt === false) {
                    echo json_encode(['status' => 'error', 'message' => 'Prepare failed: ' . htmlspecialchars($mysqli->error)]);
                    exit();
                }

                $reg_step = 'null';
                $stmt->bind_param("sss", $img_path, $reg_step, $chap);

                if ($stmt->execute()) {
                    
                    // Generate a unique token
$token = bin2hex(random_bytes(32));

// Insert into the email_confirmation table
$sql = "INSERT INTO email_confirmation (email, token, created_at) VALUES ('$chap', '$token', NOW())";
$mysqli->query($sql);

// Generate the confirmation link
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$siteUrl = $protocol . '://' . $_SERVER['HTTP_HOST'];
$confirmationLink = $siteUrl . "/secure/confirm-email.php?source=" . $token;
                    
                    
                    
                    
	$sqlnew1 = mysqli_query($con,"SELECT * FROM users WHERE email = '$chap' ");


		$rowe = mysqli_fetch_assoc($sqlnew1);
$fullname  = $rowe['firstname'].' '.$rowe['middlename'].' '.$rowe['lastname'];

                    $account_num  = $rowe['account_num'];
                                        $account_type  = $rowe['account_type'];
                    $usercurrency  = $rowe['usercurrency'];
                    $address  = $rowe['address'];
                                        $created_at  = $rowe['created_at'];



                    include 'mail.php' ;
                    echo json_encode(['status' => 'success', 'message' => 'File successfully uploaded and database updated.']);
                } else {
                    echo json_encode(['status' => 'error', 'message' => 'Error updating database: ' . htmlspecialchars($stmt->error)]);
                }

                $stmt->close();
            } else {
                echo json_encode(['status' => 'error', 'message' => 'File upload failed.']);
            }
        } else {
            echo json_encode(['status' => 'error', 'message' => 'File upload error: ' . $file['error']]);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'No file was uploaded.']);
    }

    // Close connection
    $mysqli->close();
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
}
?>
