<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header("Access-Control-Allow-Methods: GET, POST");
header("Allow: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Origin");

require_once "../database.php";

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    $email = $_POST['email'] ?? null;
    $name = $_POST['name'] ?? null;
    $sex = $_POST['sex'] ?? null;
    $address = $_POST['address'] ?? null;
    // If results or profile_code are missing, default to empty string
    $results = $_POST['results'] ?? "";
    $profile_code = $_POST['profile_code'] ?? "";
    $bio = $_POST['bio'] ?? null;

    // Array to store missing fields (except results and profile_code which are not mandatory)
    $missing_fields = [];

    if (!$email) $missing_fields[] = 'email';
    if (!$name) $missing_fields[] = 'name';
    if (!$sex) $missing_fields[] = 'sex';
    if (!$address) $missing_fields[] = 'address';
    if (!$bio) $missing_fields[] = 'bio';

    // Check if there are any missing fields
    if (!empty($missing_fields)) {
        echo json_encode([
            "status" => "error",
            "message" => "The following fields are required: " . implode(', ', $missing_fields)
        ]);
        exit;
    }

    $imageUrl = null;

    // Handle image upload if available
    if (isset($_FILES['image']) && $_FILES['image']['error'] === 0) {
        $imageTmpPath = $_FILES['image']['tmp_name'];
        $imageName = uniqid('profile_') . '_' . basename($_FILES['image']['name']);

        $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/mobile/uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $imagePath = $uploadDir . $imageName;
        $imageUrl = 'https://schoolmata.com.ng/mobile/uploads/' . $imageName;

        if (!move_uploaded_file($imageTmpPath, $imagePath)) {
            echo json_encode([
                "status" => "error",
                "message" => "Failed to upload image"
            ]);
            exit;
        }
    }

    try {
        if ($imageUrl) {
            $stmt = $conn->prepare(
                "UPDATE users SET name = :name, sex = :sex, address = :address, results = :results, profile_code = :profile_code, image = :image, bio = :bio WHERE email = :email"
            );
            $stmt->execute([
                'name' => $name,
                'sex' => $sex,
                'address' => $address,
                'results' => $results,
                'profile_code' => $profile_code,
                'image' => $imageUrl,
                'email' => $email,
                'bio'=> $bio
            ]);
        } else {
            $stmt = $conn->prepare(
                "UPDATE users SET name = :name, sex = :sex, address = :address, results = :results, profile_code = :profile_code, bio = :bio WHERE email = :email"
            );
            $stmt->execute([
                'name' => $name,
                'sex' => $sex,
                'address' => $address,
                'results' => $results,
                'profile_code' => $profile_code,
                'email' => $email,
                'bio'=> $bio
            ]);
        }

        echo json_encode([
            "status" => "success",
            "message" => "User profile updated successfully"
        ]);
    } catch (PDOException $e) {
        echo json_encode([
            "status" => "error",
            "message" => "Database error: " . $e->getMessage()
        ]);
    }
} else {
    // GET request — fetch user
    if (!isset($_GET['email'])) {
        echo json_encode([
            "status" => "error",
            "message" => "Email is required"
        ]);
        exit;
    }

    $email = $_GET['email'];

    try {
        $stmt = $conn->prepare("SELECT * FROM users WHERE email = :email LIMIT 1");
        $stmt->execute(['email' => $email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user) {
            unset($user['password']); // Don't expose password
            echo json_encode([
                "status" => "success",
                "data" => $user
            ]);
        } else {
            echo json_encode([
                "status" => "error",
                "message" => "User not found"
            ]);
        }
    } catch (PDOException $e) {
        echo json_encode([
            "status" => "error",
            "message" => "Database error: " . $e->getMessage()
        ]);
    }
}
?>
