<?php
require_once '../config/cors.php';
require_once '../config/db.php';
require_once '../includes/EmailSender.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
    exit;
}

try {
    // Collect specific inputs
    $firstName = capitalizeWords($_POST['first_name'] ?? '');
    $lastName = capitalizeWords($_POST['last_name'] ?? '');
    $middleName = capitalizeWords($_POST['middle_name'] ?? '');
    $gender = $_POST['gender'] ?? '';
    $dob = $_POST['dob'] ?? '';
    $age = $_POST['age'] ?? 0;

    $region = $_POST['region'] ?? '';
    $province = capitalizeWords($_POST['province'] ?? '');
    $city = capitalizeWords($_POST['city_municipality'] ?? '');
    $barangay = capitalizeWords($_POST['barangay'] ?? '');
    $zipcode = $_POST['zipcode'] ?? '';
    $street = capitalizeWords($_POST['street'] ?? '');

    $fbLink = $_POST['facebook_link'] ?? '';
    $viber = $_POST['viber_number'] ?? '';
    $telegram = $_POST['telegram_number'] ?? '';

    $emergencyName = capitalizeWords($_POST['emergency_contact_name'] ?? '');
    $emergencyNumber = $_POST['emergency_contact_number'] ?? '';

    $email = $_POST['email'] ?? '';
    $phone = $_POST['phone_number'] ?? '';
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    $ppsaId = $_POST['ppsa_id'] ?? '';
    $isActive = isset($_POST['is_active_nroi_member']) && $_POST['is_active_nroi_member'] === 'yes' ? 1 : 0;
    $area = trim($_POST['area'] ?? '');
    $rankInput = trim($_POST['rank'] ?? 'Regular');
    $rank = in_array(strtoupper($rankInput), ['REGULAR', 'OJT', 'INTERN']) ? (strtoupper($rankInput) === 'REGULAR' ? 'Regular' : strtoupper($rankInput)) : 'Regular';
    $role = trim($_POST['role'] ?? 'R.O');

    // Basic Validation
    if ($password !== $confirmPassword) {
        throw new Exception("Passwords do not match");
    }

    // Use NROI ID from frontend.
    $nroiId = trim($_POST['nroi_id'] ?? '');
    $isOjtOrIntern = (strtoupper($rank) === 'OJT' || strtoupper($rank) === 'INTERN');

    if (empty($nroiId)) {
        if ($isOjtOrIntern) {
            throw new Exception("Please provide your preferred NROI ID / User ID.");
        }
        throw new Exception("NROI ID is required for Regular status.");
    }

    if (strlen($nroiId) > 12) {
        throw new Exception("NROI ID cannot exceed 12 characters.");
    }

    // Area is required (except for RM): application is sent to the chosen area for AC/AAC approval
    if (empty($area) && $role !== 'RM') {
        throw new Exception("Area is required. Please choose your area in the app.");
    }

    // Double check uniqueness (backend safety)
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE nroi_id = ?");
    $stmt->execute([$nroiId]);
    if ($stmt->fetchColumn() > 0) {
        throw new Exception("The NROI ID is already registered.");
    }

    // PPSA ID: required for Regular, optional for OJT/Intern
    if (!$isOjtOrIntern && empty($ppsaId)) {
        throw new Exception("PPSA ID is required for Regular status.");
    }
    if (!empty($ppsaId)) {
        if (strlen($ppsaId) > 12) {
            throw new Exception("PPSA ID cannot exceed 12 characters.");
        }
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE ppsa_id = ?");
        $stmt->execute([$ppsaId]);
        if ($stmt->fetchColumn() > 0) {
            throw new Exception("PPSA ID already exists.");
        }
    }

    // Hash Password
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    // Profile photo (optional: from app camera capture only)
    $profilePhoto = '';
    if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] === UPLOAD_ERR_OK) {
        $targetDir = "../storage/user_profile/";
        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0777, true);
        }
        $ext = strtolower(pathinfo($_FILES["profile_photo"]["name"], PATHINFO_EXTENSION)) ?: 'jpg';
        if (!in_array($ext, ['jpg', 'jpeg', 'png'])) {
            $ext = 'jpg';
        }
        $fileName = $nroiId . '_' . time() . '.' . $ext;
        $targetFile = $targetDir . $fileName;
        if (move_uploaded_file($_FILES["profile_photo"]["tmp_name"], $targetFile)) {
            $profilePhoto = "storage/user_profile/" . $fileName;
        }
    }

    // Default Role and Status
    // $role is already assigned from POST above
    $status = 'pending'; // Default as requested

    // Generate email confirmation token
    $emailToken = bin2hex(random_bytes(32));
    $isEmailConfirmed = 0;

    // Insert into DB (users table now)
    $sql = "INSERT INTO users (
        nroi_id, ppsa_id, role, status, profile_photo, area, rank,
        first_name, last_name, middle_name, gender, dob, age,
        region, province, city_municipality, barangay, zipcode, street,
        facebook_link, viber_number, telegram_number,
        emergency_contact_name, emergency_contact_number,
        email, phone_number, password, is_active_nroi_member,
        email_confirmation_token, is_email_confirmed
    ) VALUES (
        ?, ?, ?, ?, ?, ?, ?,
        ?, ?, ?, ?, ?, ?,
        ?, ?, ?, ?, ?, ?,
        ?, ?, ?,
        ?, ?,
        ?, ?, ?, ?,
        ?, ?
    )";

    $stmt = $pdo->prepare($sql);
    $result = $stmt->execute([
        $nroiId,
        $ppsaId,
        $role,
        $status,
        $profilePhoto,
        $area ?: null,
        $rank ?: null,
        $firstName,
        $lastName,
        $middleName,
        $gender,
        $dob,
        $age,
        $region,
        $province,
        $city,
        $barangay,
        $zipcode,
        $street,
        $fbLink,
        $viber,
        $telegram,
        $emergencyName,
        $emergencyNumber,
        $email,
        $phone,
        $hashedPassword,
        $isActive,
        $emailToken,
        $isEmailConfirmed
    ]);

    if ($result) {
        // Send confirmation email
        $fullName = $firstName . ' ' . $lastName;
        $emailSent = sendEmailConfirmation($email, $fullName, $emailToken);

        echo json_encode([
            'success' => true,
            'message' => 'Registration successful! Please check your email to confirm your account.',
            'nroi_id' => $nroiId,
            'email_sent' => $emailSent
        ]);
    } else {
        throw new Exception("Registration failed during database insert.");
    }

} catch (PDOException $e) {
    if ($e->getCode() == 23000) { // Integrity constraint violation
        if (strpos($e->getMessage(), 'email')) {
            echo json_encode(['success' => false, 'message' => 'Email address already registered.']);
        } elseif (strpos($e->getMessage(), 'phone_number')) {
            echo json_encode(['success' => false, 'message' => 'Phone number already registered.']);
        } else {
            // Generic duplicate error handling if DB error message varies
            echo json_encode(['success' => false, 'message' => 'Duplicate entry found. Check email or phone.']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>