<?php 
ob_start();
require_once '../files/guardiankey.php'; 

header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR POR DEFECTO'];

try {
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    include_once 'db_connection.php';

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

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('ERROR AL DECODIFICAR DATOS');
    }

    $client_id = isset($data['id']) ? filter_var($data['id'], FILTER_VALIDATE_INT) : false;
    $first_name = isset($data['first_name']) ? filter_var(trim($data['first_name']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : '';
    $last_name = isset($data['last_name']) ? filter_var(trim($data['last_name']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : '';
    $email = !empty(trim($data['email'])) ? filter_var(trim($data['email']), FILTER_SANITIZE_EMAIL) : null;
    $phone = !empty(trim($data['phone'])) ? filter_var(trim($data['phone']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
    $mobile = !empty(trim($data['mobile'])) ? filter_var(trim($data['mobile']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;

    if ($client_id === false) {
        throw new Exception('ID DE CLIENTE INVÁLIDO O FALTANTE');
    }
    if (empty($first_name) || empty($last_name)) {
        throw new Exception('EL NOMBRE Y EL APELLIDO SON OBLIGATORIOS');
    }
    if (is_null($email) && is_null($phone) && is_null($mobile)) {
        throw new Exception('SE REQUIERE AL MENOS UN MÉTODO DE CONTACTO (EMAIL, TELÉFONO O CELULAR)');
    }

    $pdo->beginTransaction();

    $sql_check = "SELECT id FROM clients WHERE id != :current_id AND (";
    $conditions = [];
    $params_check = [':current_id' => $client_id];

    if (!is_null($email)) {
        $conditions[] = "email = :email";
        $params_check[':email'] = $email;
    }
    if (!is_null($phone)) {
        $conditions[] = "phone = :phone";
        $params_check[':phone'] = $phone;
    }
    if (!is_null($mobile)) {
        $conditions[] = "mobile = :mobile";
        $params_check[':mobile'] = $mobile;
    }

    if (!empty($conditions)) {
        $sql_check .= implode(' OR ', $conditions) . ")";
        $stmt_check = $pdo->prepare($sql_check);
        $stmt_check->execute($params_check);

        if ($stmt_check->fetch()) {
            throw new Exception('ERROR: YA EXISTE OTRO CLIENTE CON EL MISMO EMAIL, TELÉFONO FIJO O CELULAR');
        }
    }

    $stmt = $pdo->prepare("
        UPDATE clients SET
            first_name = :first_name, last_name = :last_name, email = :email,
            phone = :phone, mobile = :mobile, street_address = :street_address,
            city = :city, state_province = :state_province, zip_code = :zip_code,
            is_recurring = :is_recurring
        WHERE id = :id
    ");

    $stmt->execute([
        ':first_name' => $first_name,
        ':last_name' => $last_name,
        ':email' => $email,
        ':phone' => $phone,
        ':mobile' => $mobile,
        ':street_address' => !empty($data['street_address']) ? filter_var(trim($data['street_address']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null,
        ':city' => !empty($data['city']) ? filter_var(trim($data['city']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null,
        ':state_province' => !empty($data['state_province']) ? filter_var(trim($data['state_province']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null,
        ':zip_code' => !empty($data['zip_code']) ? filter_var(trim($data['zip_code']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null,
        ':is_recurring' => !empty($data['is_recurring']) ? 1 : 0,
        ':id' => $client_id
    ]);

    $delete_services_stmt = $pdo->prepare("DELETE FROM client_services WHERE client_id = :client_id");
    $delete_services_stmt->execute([':client_id' => $client_id]);

    $assigned_service_ids = $data['assigned_service_ids'] ?? [];
    if (!empty($assigned_service_ids) && is_array($assigned_service_ids)) {
        $insert_service_stmt = $pdo->prepare("INSERT INTO client_services (client_id, service_id) VALUES (:client_id, :service_id)");
        foreach ($assigned_service_ids as $service_id) {
            if (filter_var($service_id, FILTER_VALIDATE_INT) !== false) {
                $insert_service_stmt->execute([':client_id' => $client_id, ':service_id' => (int)$service_id]);
            } else {
                error_log("ID de servicio inválido detectado al actualizar cliente ID " . $client_id . ": " . $service_id);
            }
        }
    }

    $pdo->commit();

    $response['success'] = true;
    $response['message'] = 'GUARDADO';
    $response['client'] = $data;
    $response['client']['id'] = $client_id;

} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("PDOException en clients-update.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("Error general en clients-update.php: " . $e->getMessage());
    $response['message'] = $e->getMessage();
}

ob_end_clean();
echo json_encode($response);
exit;