<?php
require_once __DIR__ . '/../includes/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Invalid request method.');
}

// CSRF Validation
if (!validateCSRF($_POST['csrf_token'] ?? '')) {
    jsonResponse(false, 'Invalid CSRF token.');
}

// Get Form Data
$name       = sanitize($_POST['name'] ?? '');
$email      = sanitizeEmail($_POST['email'] ?? '');
$mobile     = sanitize($_POST['mobile'] ?? '');
$experience = sanitize($_POST['experience'] ?? '');

// Validation
if (empty($name) || empty($email) || empty($mobile) || empty($experience)) {
    jsonResponse(false, 'Please fill all required fields.');
}

if (!validateEmail($email)) {
    jsonResponse(false, 'Invalid email address.');
}

try {

    $db = getDB();

    // Check existing lawyer
    $check = $db->prepare("SELECT id FROM lawyers WHERE email = ? OR mobile = ?");
    $check->execute([$email, $mobile]);

    if ($check->fetch()) {
        jsonResponse(false, 'Lawyer already registered with this email or mobile.');
    }

    // Insert lawyer
    $stmt = $db->prepare("
        INSERT INTO lawyers 
        (name, email, mobile, experience_years, verification_status, status, created_at)
        VALUES
        (?, ?, ?, ?, 'pending', 1, NOW())
    ");

    $stmt->execute([
        $name,
        $email,
        $mobile,
        $experience
    ]);

    jsonResponse(true, 'Registration submitted successfully.');

} catch (Exception $e) {

    jsonResponse(false, 'Something went wrong.');

}