<?php
session_start();
require_once('../db/db_connection.php');

if (!isset($_SESSION['client_id']) || $_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: login.php');
    exit();
}

$client_id = $_POST['client_id'];

if ($client_id != $_SESSION['client_id']) {
    $_SESSION['feedback'] = ['type' => 'error', 'message' => 'Security validation error.'];
    header('Location: dashboard.php');
    exit();
}

// OBTENER Y SANITIZAR TODOS LOS CAMPOS, INCLUYENDO EL EMAIL
$first_name = filter_input(INPUT_POST, 'first_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$last_name = filter_input(INPUT_POST, 'last_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); // Usar validación de email
$phone = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$mobile = filter_input(INPUT_POST, 'mobile', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$street_address = filter_input(INPUT_POST, 'street_address', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$city = filter_input(INPUT_POST, 'city', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$state_province = filter_input(INPUT_POST, 'state_province', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$zip_code = filter_input(INPUT_POST, 'zip_code', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$is_recurring = isset($_POST['is_recurring']) ? 1 : 0;

if ($email === false) {
    $_SESSION['feedback'] = ['type' => 'error', 'message' => 'The email format provided is not valid.'];
    header('Location: dashboard.php');
    exit();
}

try {
    // AÑADIR EL CAMPO 'email' A LA CONSULTA DE ACTUALIZACIÓN
    $stmt = $pdo->prepare(
        "UPDATE clients SET 
            first_name = ?, last_name = ?, email = ?, phone = ?, mobile = ?, 
            street_address = ?, city = ?, state_province = ?, zip_code = ?, is_recurring = ?
        WHERE id = ?"
    );
    
    $stmt->execute([
        $first_name, $last_name, $email, $phone, $mobile, 
        $street_address, $city, $state_province, $zip_code, $is_recurring,
        $client_id
    ]);

    $_SESSION['feedback'] = ['type' => 'success', 'message' => 'Profile updated successfully!'];

} catch (PDOException $e) {
    error_log("Error updating profile: " . $e->getMessage());
    // Error para email duplicado
    if ($e->getCode() == 23000) {
        $_SESSION['feedback'] = ['type' => 'error', 'message' => 'This email is already in use by another client.'];
    } else {
        $_SESSION['feedback'] = ['type' => 'error', 'message' => 'An error occurred while saving the changes.'];
    }
}

header('Location: dashboard.php');
exit();
?>