<?php
require_once 'config/database.php';
require_once 'utils/helpers.php';

try {

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        Helpers::sendResponse(false, 'Method not allowed', null, 405);
    }

    $data = json_decode(file_get_contents("php://input"));

    // Validate required fields
    if (empty($data->email)) {
        Helpers::sendResponse(false, 'Email is required', null, 400);
    }

    // Validate email format
    if (!Helpers::validateEmail($data->email)) {
        Helpers::sendResponse(false, 'Invalid email format', null, 400);
    }

    $database = new Database();
    $db = $database->getConnection();

    // Check if email already exists
    $query = "SELECT id, is_verified, role_id, department_id FROM users WHERE email = :email";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':email', $data->email);
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user['is_verified']) {
            // Generate new OTP and expiry date
            $otp = Helpers::generateOTP();
            $expiresAt = date('Y-m-d H:i:s', strtotime('+15 minutes'));

            // Update the user record with the new OTP and expiry
            $updateQuery = "UPDATE users SET verification_code = :verification_code, verification_expires = :verification_expires WHERE email = :email";
            $updateStmt = $db->prepare($updateQuery);
            $updateStmt->bindParam(':verification_code', $otp);
            $updateStmt->bindParam(':verification_expires', $expiresAt);
            $updateStmt->bindParam(':email', $data->email);

            if ($updateStmt->execute()) {
                // Resend OTP via email
                $subject = "Hopepress Chapel - Resend Email Verification";
                $body = "Your new verification code is: " . $otp . "\n\nThis code will expire in 15 minutes.";
                Helpers::sendEmail($data->email, $subject, $body);

                Helpers::sendResponse(true, 'New verification code sent to your email', [
                    'email' => $data->email,
                    'otp' => $otp
                ], 200);
            } else {
                Helpers::sendResponse(false, 'Failed to resend verification code', null, 500);
            }
        } else if (empty($user['role_id']) || empty($user['department_id'])) {
            Helpers::sendResponse(true, 'Partial registration detected. Redirecting you to complete your registration.', [
                'user_id' => $user['id']
            ], 200);
        }
        Helpers::sendResponse(false, 'Email already registered. Kindly login.', null, 409);
    }

    // Generate OTP
    $otp = Helpers::generateOTP();
    $expiresAt = date('Y-m-d H:i:s', strtotime('+15 minutes'));

    // Create temporary user record with OTP
    $query = "INSERT INTO users (email, first_name, last_name, phone_number, gender, password, verification_code, verification_expires, is_verified) 
          VALUES (:email, '', '', '', NULL, '', :verification_code, :verification_expires, FALSE)";

    $stmt = $db->prepare($query);
    $stmt->bindParam(':email', $data->email);
    $stmt->bindParam(':verification_code', $otp);
    $stmt->bindParam(':verification_expires', $expiresAt);

    if ($stmt->execute()) {
        // Send OTP via email
        $subject = "Hopepress Chapel - Email Verification";
        $body = "Your verification code is: " . $otp . "\n\nThis code will expire in 15 minutes.";
        Helpers::sendEmail($data->email, $subject, $body);

        Helpers::sendResponse(true, 'Verification code sent to your email', [
            'email' => $data->email,
            'otp' => $otp
        ], 201);
    } else {
        Helpers::sendResponse(false, 'Registration failed', null, 500);
    }
} catch (PDOException $e) {
    ErrorLogger::logDatabaseError($e, $logQuery ?? 'Registration query', [
        'endpoint' => 'auth/register',
        'user_id' => $user->user_id ?? 'unknown'
    ]);
    Helpers::sendResponse(false, 'An error occurred during registration', null, 500);
} catch (Exception $e) {
    ErrorLogger::logError($e, [
        'endpoint' => 'auth/register'
    ]);
    Helpers::sendResponse(false, 'An unexpected error occurred', null, 500);
}
