<?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;
    $results = $_POST['results'] ?? "";
    $profile_code = $_POST['profile_code'] ?? "";
    $bio = $_POST['bio'] ?? null;

    $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';

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

    try {
        // 1. Get POST UTME fee
        $feeStmt = $conn->query("SELECT postutme_fee FROM settings LIMIT 1");
        $feeResult = $feeStmt->fetch(PDO::FETCH_ASSOC);
        $postutme_fee = floatval($feeResult['postutme_fee'] ?? 0);

        // 2. Get user balance and ID
        $userStmt = $conn->prepare("SELECT id, balance FROM users WHERE email = :email");
        $userStmt->execute(['email' => $email]);
        $user = $userStmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            echo json_encode([
                "status" => "error",
                "message" => "User not found"
            ]);
            exit;
        }

        $user_id = $user['id'];
        $user_balance = floatval($user['balance']);

        if ($user_balance < $postutme_fee) {
            echo json_encode([
                "status" => "error",
                "message" => "Insufficient balance. You need ₦" . number_format($postutme_fee, 2)
            ]);
            exit;
        }

        // 3. Deduct fee from user balance
        $new_balance = $user_balance - $postutme_fee;
        $updateBalance = $conn->prepare("UPDATE users SET balance = :balance WHERE email = :email");
        $updateBalance->execute([
            'balance' => $new_balance,
            'email' => $email
        ]);

        // 4. Update profile info
        $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,
            'bio' => $bio,
            'email' => $email
        ]);

        // 5. Log transaction
        $reference = 'PUTME|' . rand(10, 99) . '|' . date('YmdHis') . '|' . rand(100000, 999999);
        $description = "POST-UTME Fee deduction of ₦" . number_format($postutme_fee, 2);

        $insertTxn = $conn->prepare("INSERT INTO transactions (user_id, amount, description, reference, status, created_at) 
                                     VALUES (:user_id, :amount, :description, :reference, 'success', NOW())");
        $insertTxn->execute([
            'user_id' => $user_id,
            'amount' => $postutme_fee,
            'description' => $description,
            'reference' => $reference
        ]);

        // 6. Update has_paid to yes
        $updatePaid = $conn->prepare("UPDATE users SET has_paid = 'yes' WHERE id = :id");
        $updatePaid->execute(['id' => $user_id]);

        // 7. Final response
        echo json_encode([
            "status" => "success",
            "message" => "Profile updated, ₦" . number_format($postutme_fee, 2) . " deducted, transaction saved, and payment marked as complete."
        ]);

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