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

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

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('MÉTODO NO PERMITIDO');
    }

    $pdo->beginTransaction();

    $full_name = htmlspecialchars(strip_tags($_POST['full_name'] ?? ''));
    $company_name = htmlspecialchars(strip_tags($_POST['company_name'] ?? ''));
    $license_number = htmlspecialchars(strip_tags($_POST['license_number'] ?? ''));
    $phone_primary = htmlspecialchars(strip_tags($_POST['phone_primary'] ?? ''));
    $phone_secondary = htmlspecialchars(strip_tags($_POST['phone_secondary'] ?? ''));
    $whatsapp = htmlspecialchars(strip_tags($_POST['whatsapp'] ?? ''));
    $site_email = htmlspecialchars(strip_tags($_POST['site_email'] ?? ''));
    $website_url = htmlspecialchars(strip_tags($_POST['website_url'] ?? ''));

    $target_id = 1;

    $stmt = $pdo->prepare("SELECT id FROM business_info WHERE id = ?");
    $stmt->execute([$target_id]);
    $currentRecord = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($currentRecord) {
        $sql = "UPDATE business_info SET full_name=?, company_name=?, license_number=?, phone_primary=?, phone_secondary=?, whatsapp=?, site_email=?, website_url=? WHERE id=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$full_name, $company_name, $license_number, $phone_primary, $phone_secondary, $whatsapp, $site_email, $website_url, $target_id]);
    } else {
        $sql = "INSERT INTO business_info (id, full_name, company_name, license_number, phone_primary, phone_secondary, whatsapp, site_email, website_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$target_id, $full_name, $company_name, $license_number, $phone_primary, $phone_secondary, $whatsapp, $site_email, $website_url]);
    }

    $pdo->commit();
    $response = ['success' => true, 'message' => 'GUARDADO'];

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

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