<?php
session_start();
require_once __DIR__ . '/../includes/auth.php';
require_role('admin');
require_once __DIR__ . '/../includes/helpers.php';

$db = db();

$clientId = $_GET['id'] ?? null;
$client = [
    'name' => '',
    'nip' => '',
    'street' => '',
    'city' => '',
    'postal_code' => '',
    'credit_limit' => 0,
];
$isNewClient = !$clientId;
$pageTitle = $isNewClient ? 'Dodaj nowego klienta' : 'Edytuj klienta';
$errorMessage = '';
$successMessage = '';

if ($clientId) {
    $stmt = $db->prepare("SELECT * FROM clients WHERE id = :id");
    $stmt->execute(['id' => $clientId]);
    $client = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$client) {
        die("Klient nie został znaleziony.");
    }

    // Calculate used credit
    $used_credit = $client['credit_limit'] - $client['credit_balance'];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'] ?? '';
    $tax_id = $_POST['tax_id'] ?? '';
    $address = $_POST['address'] ?? '';
    $city = $_POST['city'] ?? '';
    $zip_code = $_POST['zip_code'] ?? '';
    $credit_limit = $_POST['credit_limit'] ?? 0;

    if (empty($name)) {
        $errorMessage = 'Nazwa klienta jest wymagana.';
    } else {
        try {
            if ($isNewClient) {
                $stmt = $db->prepare("INSERT INTO clients (name, nip, street, city, postal_code, credit_limit) VALUES (:name, :tax_id, :address, :city, :zip_code, :credit_limit)");
            } else {
                $stmt = $db->prepare("UPDATE clients SET name = :name, nip = :tax_id, street = :address, city = :city, postal_code = :zip_code, credit_limit = :credit_limit WHERE id = :id");
            }
            
            $params = [
                'name' => $name,
                'tax_id' => $tax_id,
                'address' => $address,
                'city' => $city,
                'zip_code' => $zip_code,
                'credit_limit' => $credit_limit
            ];

            if (!$isNewClient) {
                $params['id'] = $clientId;
            }

            $stmt->execute($params);

            if ($isNewClient) {
                $clientId = $db->lastInsertId();
                header('Location: clients.php?status=created');
                exit;
            }
            $successMessage = 'Dane klienta zostały zaktualizowane.';
            // Re-fetch data to display updated values
            $stmt = $db->prepare("SELECT * FROM clients WHERE id = :id");
            $stmt->execute(['id' => $clientId]);
            $client = $stmt->fetch(PDO::FETCH_ASSOC);

        } catch (PDOException $e) {
            $errorMessage = 'Wystąpił błąd podczas zapisywania danych klienta.';
            // error_log($e->getMessage()); // Uncomment for debugging
        }
    }
}
?>
<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($pageTitle); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<?php require_once __DIR__ . '/menu.php'; ?>
<div class="container mt-4">
    <div class="card">
        <div class="card-header">
            <h1><?php echo htmlspecialchars($pageTitle); ?></h1>
        </div>
        <div class="card-body">
            <?php if ($errorMessage): ?>
                <div class="alert alert-danger"><?php echo $errorMessage; ?></div>
            <?php endif; ?>
            <?php if ($successMessage): ?>
                <div class="alert alert-success"><?php echo $successMessage; ?></div>
            <?php endif; ?>
            <form method="post">
                <div class="mb-3">
                    <label for="name" class="form-label">Nazwa firmy</label>
                    <input type="text" class="form-control" id="name" name="name" value="<?php echo htmlspecialchars($client['name'] ?? ''); ?>" required>
                </div>
                <div class="mb-3">
                    <label for="tax_id" class="form-label">NIP</label>
                    <input type="text" class="form-control" id="tax_id" name="tax_id" value="<?php echo htmlspecialchars($client['nip'] ?? ''); ?>">
                </div>
                <div class="mb-3">
                    <label for="address" class="form-label">Adres</label>
                    <input type="text" class="form-control" id="address" name="address" value="<?php echo htmlspecialchars($client['street'] ?? ''); ?>">
                </div>
                <div class="mb-3">
                    <label for="zip_code" class="form-label">Kod pocztowy</label>
                    <input type="text" class="form-control" id="zip_code" name="zip_code" value="<?php echo htmlspecialchars($client['postal_code'] ?? ''); ?>">
                </div>
                 <div class="mb-3">
                    <label for="city" class="form-label">Miasto</label>
                    <input type="text" class="form-control" id="city" name="city" value="<?php echo htmlspecialchars($client['city'] ?? ''); ?>">
                </div>
                <div class="mb-3">
                    <label for="credit_limit" class="form-label">Limit kredytu kupieckiego</label>
                    <input type="number" step="0.01" class="form-control" id="credit_limit" name="credit_limit" value="<?php echo htmlspecialchars($client['credit_limit'] ?? '0'); ?>">
                </div>
                <?php if ($clientId): ?>
                <div class="mb-3">
                    <label class="form-label">Wykorzystany kredyt</label>
                    <p class="form-control-plaintext"><?php echo number_format($used_credit, 2, ',', ' '); ?> PLN</p>
                </div>
                <div class="mb-3">
                    <label class="form-label">Dostępny kredyt</label>
                    <p class="form-control-plaintext fw-bold <?php echo (($client['credit_limit'] - $used_credit) < 0) ? 'text-danger' : 'text-success'; ?>">
                        <?php echo number_format($client['credit_limit'] - $used_credit, 2, ',', ' '); ?> PLN
                    </p>
                </div>
                <?php endif; ?>
                <button type="submit" class="btn btn-primary">Zapisz</button>
                <a href="clients.php" class="btn btn-secondary">Anuluj</a>
            </form>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
