<?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');

// Function to sanitize input
function sanitize_input($input) {
    return htmlspecialchars(stripslashes(trim($input)));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['user_id'], $_POST['auth'])) {
    include 'db/config.php';

    // Retrieve and sanitize input
    $inputs = [
        'user_id', 'auth', 'firstname', 'lastname',
        'city', 'state', 'country',
        'dob', 'height', 'body_color', 'gender', 'profession'
    ];

    $data = [];
    foreach ($inputs as $field) {
        $data[$field] = sanitize_input($_POST[$field] ?? '');
    }

    // Validate required fields
    $required_fields = [
        'user_id', 'auth', 'firstname', 'lastname',
        'city', 'state', 'country',
        'dob', 'height', 'body_color', 'gender', 'profession'
    ];

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

    date_default_timezone_set("Africa/Lagos");
    $date_reg = date("Y-m-d H:i:s");

    try {
        // Check user existence
        $user_query = $con->prepare("SELECT * FROM users WHERE user_id = ? AND auth = ?");
        $user_query->bind_param("ss", $data['user_id'], $data['auth']);
        $user_query->execute();
        $user_result = $user_query->get_result();

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

        // Update query
        $query1 = "
            UPDATE users SET 
                firstname = ?, lastname = ?, 
                city = ?, state = ?, country = ?, 
                dob = ?, height = ?, body_color = ?, gender = ?, profession = ? 
            WHERE user_id = ? AND auth = ?
        ";
        $stmt1 = $con->prepare($query1);
        $stmt1->bind_param(
            "ssssssssssss", 
            $data['firstname'], $data['lastname'],
            $data['city'], $data['state'], $data['country'], 
            $data['dob'], $data['height'], $data['body_color'], 
            $data['gender'], $data['profession'], 
            $data['user_id'], $data['auth']
        );
        $stmt1->execute();

        echo json_encode(['status' => true, 'user_id' => $data['user_id'], 'success' => 'Profile updated']);
    } catch (Exception $e) {
        echo json_encode(['status' => false, 'success' => $e->getMessage()]);
    } finally {
        $con->close();
    }
} else {
    echo json_encode(['status' => false, 'success' => 'Invalid request']);
}
?>
