<?php
declare(strict_types=1);

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';
require_once __DIR__ . '/../../core/Validator.php';
require_once __DIR__ . '/../../core/Logger.php';
require_once __DIR__ . '/../../security/auth_guard_api.php';
require_once __DIR__ . '/../../security/csrf_guard.php';

/**
 * Allow only POST
 */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Response::error('Method not allowed', 405);
}

/**
 * Enforce JSON
 */
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (stripos($contentType, 'application/json') === false) {
    Response::error('Invalid content type', 415);
}

/**
 * Decode JSON safely
 */
$data = json_decode(file_get_contents('php://input'), true);

if (!is_array($data)) {
    Response::error('Invalid JSON payload', 400);
}

/**
 * Mandatory fields validation
 */
Validator::required($data, [
    'dealer_name',
    'state_id',
    'city_id',
    'latitude',
    'longitude',
    'cst_id',
    'dealer_type_id'
]);

$db = Database::getInstance();

try {
    $db->beginTransaction();

    /**
     * Validate CST manager
     */
    $stmt = $db->prepare(
        "SELECT id FROM cst_managers WHERE id = :id AND status = 'Active'"
    );
    $stmt->execute(['id' => (int)$data['cst_id']]);
    if (!$stmt->fetch()) {
        Response::error('Invalid CST manager', 422);
    }

    /**
     * Validate dealer type
     */
    $stmt = $db->prepare(
        "SELECT id FROM dealer_types WHERE id = :id AND status = 'Active'"
    );
    $stmt->execute(['id' => (int)$data['dealer_type_id']]);
    if (!$stmt->fetch()) {
        Response::error('Invalid dealer type', 422);
    }

    /**
     * Validate state
     */
    $stmt = $db->prepare(
        "SELECT id FROM states WHERE id = :id AND status = 'Active'"
    );
    $stmt->execute(['id' => (int)$data['state_id']]);
    if (!$stmt->fetch()) {
        Response::error('Invalid state', 422);
    }

    /**
     * Validate city
     */
    $stmt = $db->prepare(
        "SELECT city_name FROM cities 
         WHERE id = :id AND state_id = :state_id AND status = 'Active'"
    );
    $stmt->execute([
        'id' => (int)$data['city_id'],
        'state_id' => (int)$data['state_id']
    ]);
    $city = $stmt->fetch();

    if (!$city) {
        Response::error('Invalid city for selected state', 422);
    }

    /**
     * Slug generation
     */
    $slugBase = strtolower(
        trim($data['dealer_name']) . '-kingkoil-showroom-in-' . $city['city_name']
    );
    $slug = trim(preg_replace('/[^a-z0-9]+/', '-', $slugBase), '-');

    /**
     * Ensure slug uniqueness
     */
    $stmt = $db->prepare("SELECT id FROM dealers WHERE slug = :slug");
    $stmt->execute(['slug' => $slug]);
    if ($stmt->fetch()) {
        Response::error('Dealer with same name already exists in this city', 409);
    }

    /**
     * Insert dealer
     */
    $stmt = $db->prepare("
        INSERT INTO dealers (
            dealer_name, slug, cst_id, dealer_type_id,
            contact_person, email, phone, alt_phone,
            address_line1, address_line2,
            state_id, city_id, pincode,
            latitude, longitude, dealer_details,
            display_order, status, approval_status, content_status,
            created_by, created_at
        ) VALUES (
            :dealer_name, :slug, :cst_id, :dealer_type_id,
            :contact_person, :email, :phone, :alt_phone,
            :address_line1, :address_line2,
            :state_id, :city_id, :pincode,
            :latitude, :longitude, :dealer_details,
            :display_order, 'Draft', 'Pending', 'Not Updated',
            :created_by, NOW()
        )
    ");

    $stmt->execute([
        'dealer_name'    => trim($data['dealer_name']),
        'slug'           => $slug,
        'cst_id'         => (int)$data['cst_id'],
        'dealer_type_id' => (int)$data['dealer_type_id'],
        'contact_person' => $data['contact_person'] ?? null,
        'email'          => $data['email'] ?? null,
        'phone'          => $data['phone'] ?? null,
        'alt_phone'      => $data['alt_phone'] ?? null,
        'address_line1'  => $data['address_line1'] ?? null,
        'address_line2'  => $data['address_line2'] ?? null,
        'state_id'       => (int)$data['state_id'],
        'city_id'        => (int)$data['city_id'],
        'pincode'        => $data['pincode'] ?? null,
        'latitude'       => $data['latitude'],
        'longitude'      => $data['longitude'],
        'dealer_details' => $data['dealer_details'] ?? null,
        'display_order'  => $data['display_order'] ?? 1,
        'created_by'     => $_SESSION['employee_id']
    ]);

    $db->commit();

    Logger::auth('Dealer created', [
        'dealer' => $data['dealer_name'],
        'by' => $_SESSION['employee_id']
    ]);

    Response::success('Dealer created successfully', ['slug' => $slug]);

} catch (Throwable $e) {
    $db->rollBack();
    Logger::error('Dealer create failed', ['error' => $e->getMessage()]);
    Response::error('Failed to create dealer', 500);
}
