<?php
require_once 'config.php';
checkAccess(['admin', 'programmer', 'board']);

$data = $REQUEST_DATA;

if (!isset($data['rif']) || !isset($data['name'])) {
    response(["error" => "Datos obligatorios faltantes (RIF/Nombre)"], 400);
}

try {
    $sql = "INSERT INTO providers 
            (rif, name, contact_person, email, phone_primary, phone_office, country, service_type, tax_address) 
            VALUES (:rif, :name, :cp, :email, :pp, :po, :country, :st, :ta)
            ON DUPLICATE KEY UPDATE 
            name = :name_upd, contact_person = :cp_upd, email = :email_upd, 
            phone_primary = :pp_upd, phone_office = :po_upd, service_type = :st_upd, 
            tax_address = :ta_upd";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':rif' => $data['rif'],
        ':name' => $data['name'],
        ':cp' => $data['contactPerson'] ?? null,
        ':email' => $data['email'] ?? null,
        ':pp' => $data['phonePrimary'],
        ':po' => $data['phoneOffice'] ?? null,
        ':country' => $data['country'] ?? 'Venezuela',
        ':st' => $data['serviceType'] ?? 'Mantenimiento',
        ':ta' => $data['taxAddress'] ?? null,
        ':name_upd' => $data['name'],
        ':cp_upd' => $data['contactPerson'] ?? null,
        ':email_upd' => $data['email'] ?? null,
        ':pp_upd' => $data['phonePrimary'],
        ':po_upd' => $data['phoneOffice'] ?? null,
        ':st_upd' => $data['serviceType'] ?? 'Mantenimiento',
        ':ta_upd' => $data['taxAddress'] ?? null
    ]);

    logSystemAction("GESTIONÓ Proveedor: " . $data['name'] . " (" . $data['rif'] . ")", "PROVEEDORES");
    response(["success" => true]);
} catch (PDOException $e) {
    response(["error" => "Fallo al guardar: " . $e->getMessage()], 500);
}