<?php
session_start();

$host = 'localhost';
$database = 'C:\Program Files (x86)\Common Files\Aspel\Sistemas Aspel\SAE7.00\Ejemplos\Ejemplos.fdb';
$username = 'SYSDBA';
$password = 'masterkey';

header('Content-Type: application/json');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (!isset($_POST['clave'])) {
        echo json_encode(['diasCredito' => 0]);
        exit;
    }

    $clave = $_POST['clave'];

    try {
        $dbh = new PDO("firebird:host=$host;dbname=$database;charset=UTF8", $username, $password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $dbh->prepare("SELECT CON_CREDITO, DIASCRED FROM PROV01 WHERE CLAVE = :clave");
        $stmt->bindParam(':clave', $clave);
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        $diasCredito = ($row && strtoupper($row['CON_CREDITO']) === 'S') ? (int)($row['DIASCRED'] ?? 0) : 0;

        echo json_encode(['diasCredito' => $diasCredito]);
    } catch (PDOException $e) {
        echo json_encode([
            'diasCredito' => 0,
            'error' => 'Error de conexión o consulta: ' . $e->getMessage()
        ]);
    }
}
