<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

if (isset($_POST['user_id']) && isset($_POST['auth'])) {
    include 'config.php';

    function check_input($par) {
        return htmlspecialchars(stripslashes(trim($par)));
    }

    $user_id = mysqli_real_escape_string($con, $_POST['user_id']);
    $auth = mysqli_real_escape_string($con, $_POST['auth']);
    $firstname = check_input($_POST['firstname'] ?? '');
    $midname = check_input($_POST['midname'] ?? '');
    $lastname = check_input($_POST['lastname'] ?? '');
    $address = check_input($_POST['address'] ?? '');
    $city = check_input($_POST['city'] ?? '');
    $state = check_input($_POST['state'] ?? '');
    $country = check_input($_POST['country'] ?? '');
    $country_code = check_input($_POST['country_code'] ?? '');
    $whatsapp = check_input($_POST['whatsapp'] ?? '');
    $phone = check_input($_POST['phone'] ?? '');
    $email = check_input($_POST['email'] ?? '');

    // Validate all required fields
    $required_fields = [
        'user_id', 'auth', 'firstname', 'lastname', 
        'address', 'city', 'state', 'country', 'country_code', 
        'whatsapp', 'phone', 'email'
    ];

    foreach ($required_fields as $field) {
        if (empty($$field)) {
            echo json_encode(['status' => false, 'success' => "$field is required"]);
            exit();
        }
    }

    // Check if the user exists
    $check_user_query = $con->prepare("SELECT * FROM users WHERE user_id = ? AND auth = ?");
    if (!$check_user_query) {
        echo json_encode(['status' => false, 'success' => 'Database error: ' . $con->error]);
        exit();
    }
    $check_user_query->bind_param("ss", $user_id, $auth);
    $check_user_query->execute();
    $user_result = $check_user_query->get_result();

    if ($user_result->num_rows === 0) {
        echo json_encode(['status' => false, 'success' => 'User not found']);
        exit();
    }

    // Prepare the SQL update query
    $update_query = $con->prepare("
        UPDATE users 
        SET 
            firstname = ?, 
            lastname = ?, 
            midname = ?, 
            address = ?, 
            city = ?, 
            state = ?, 
            country = ?, 
            country_code = ?, 
            whatsapp = ?, 
            phone = ?, 
            status = 'Completed'
        WHERE 
            user_id = ? AND auth = ?
    ");

    if (!$update_query) {
        echo json_encode(['status' => false, 'success' => 'Database error: ' . $con->error]);
        exit();
    }

    // Bind parameters
    $update_query->bind_param(
        "sssssssssss",
        $firstname,
        $lastname,
        $midname,
        $address,
        $city,
        $state,
        $country,
        $country_code,
        $whatsapp,
        $phone,
        $user_id,
        $auth
    );

    if ($update_query->execute()) {
        $subject = "Your Verification Code!";
        $message = "
            <html>
                <body>
                    <p>Dear $firstname,</p>
                    <p>You just created an account on Eduabroad.</p>
                    <p>Your Agent number is AG$user_id.</p>
                </body>
            </html>
        ";

        $mail = new PHPMailer();
        require 'mail_head.php';
        $mail->setFrom('dev@diimdevs.com', 'Eduabroad');
        $mail->addAddress($email);
        $mail->addBcc("diimtech@gmail.com");
        $mail->Subject = $subject;
        $mail->msgHTML($message);

        if ($mail->send()) {
            $status = true;
            $suc = "Profile updated successfully and email sent";
        } else {
            $status = false;
            $suc = "Profile updated, but email failed to send";
        }
    } else {
        $status = false;
        $suc = "Update failed: " . $update_query->error;
    }

    $check_user_query->close();
    $update_query->close();
    $con->close();

    echo json_encode([
        'status' => $status,
        'success' => $suc,
        'user_id' => $user_id,
        'auth' => $auth,
    ]);
} else {
    echo json_encode(['status' => false, 'success' => 'Invalid request']);
}
?>
