<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
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';

// update logic

$data = json_decode(file_get_contents('php://input'), true);

Validator::required($data, ['dealer_id']);

$dealerId = (int)$data['dealer_id'];

$db = Database::getInstance();

/**
 * Fetch existing dealer
 */
$stmt = $db->prepare("
    SELECT d.*, c.city_name
    FROM dealers d
    JOIN cities c ON c.id = d.city_id
    WHERE d.id = :id
");
$stmt->execute(['id' => $dealerId]);
$dealer = $stmt->fetch();

if (!$dealer) {
    Response::error('Dealer not found', 404);
}

/**
 * Allowed update fields
 */
$allowedFields = [
    'dealer_name',
    'dealer_type_id',
    'cst_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'
];

$updates = [];
$params  = ['id' => $dealerId];

/**
 * Helper: slug generator
 */
function dealerSlug(string $name, string $city): string
{
    $slug = strtolower($name . '-kingkoil-showroom-in-' . $city);
    $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
    return trim($slug, '-');
}

/**
 * Process fields
 */
foreach ($allowedFields as $field) {
    if (!array_key_exists($field, $data)) {
        continue;
    }

    switch ($field) {

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

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

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

        case 'city_id':
            if (!isset($data['state_id']) && !isset($dealer['state_id'])) {
                Response::error('State required for city update', 422);
            }

            $stateId = $data['state_id'] ?? $dealer['state_id'];

            $stmt = $db->prepare("
                SELECT city_name FROM cities 
                WHERE id = :id AND state_id = :state_id AND status = 'Active'
            ");
            $stmt->execute([
                'id' => $data[$field],
                'state_id' => $stateId
            ]);

            $city = $stmt->fetch();
            if (!$city) {
                Response::error('Invalid city for selected state', 422);
            }

            $updates[] = "city_id = :city_id";
            $params['city_id'] = (int)$data[$field];

            // regenerate slug later
            $newCityName = $city['city_name'];
            break;

        case 'dealer_name':
            $updates[] = "dealer_name = :dealer_name";
            $params['dealer_name'] = trim($data[$field]);
            $newDealerName = trim($data[$field]);
            break;

        default:
            $updates[] = "$field = :$field";
            $params[$field] = $data[$field];
    }
}

/**
 * Slug regeneration if name or city changed
 */
if (isset($newDealerName) || isset($newCityName)) {
    $name = $newDealerName ?? $dealer['dealer_name'];
    $city = $newCityName ?? $dealer['city_name'];
    $slug = dealerSlug($name, $city);

    // ensure uniqueness
    $stmt = $db->prepare("
        SELECT id FROM dealers 
        WHERE slug = :slug AND id != :id
    ");
    $stmt->execute(['slug' => $slug, 'id' => $dealerId]);
    if ($stmt->fetch()) {
        Response::error('Duplicate dealer slug detected', 409);
    }

    $updates[] = "slug = :slug";
    $params['slug'] = $slug;
}

if (empty($updates)) {
    Response::error('No valid fields provided for update', 422);
}

/**
 * Execute update
 */
$sql = "
UPDATE dealers
SET " . implode(', ', $updates) . ",
    updated_by = :updated_by,
    updated_at = NOW()
WHERE id = :id
";

$params['updated_by'] = $_SESSION['employee_id'];

$stmt = $db->prepare($sql);
$stmt->execute($params);

Logger::auth('Dealer updated', [
    'dealer_id' => $dealerId,
    'by' => $_SESSION['employee_id']
]);

Response::success('Dealer updated successfully');
