<?php
require_once __DIR__ . '/../includes/init.php';
require_role(['admin', 'handlowiec', 'supplier']);

$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.");
    }
    $available_credit = $client['credit_balance'];
    $used_credit = $client['credit_limit'] - $client['credit_balance'];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Separate logic for payback and cancellation, which have their own submit buttons
    if (isset($_POST['payback_submit']) && isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin') {
        $payback_amount = (float)($_POST['payback_amount'] ?? 0);
        $used_credit_for_validation = $client['credit_limit'] - $client['credit_balance'];

        if ($payback_amount <= 0) {
            $errorMessage = 'Kwota spłaty musi być większa od zera.';
        } elseif ($payback_amount > $used_credit_for_validation) {
            $errorMessage = "Kwota spłaty nie może być wyższa niż wykorzystany kredyt (" . number_format($used_credit_for_validation, 2, ',', ' ') . " PLN).";
        } else {
            try {
                $new_credit_balance = $client['credit_balance'] + $payback_amount;
                
                $stmt = $db->prepare("UPDATE clients SET credit_balance = :credit_balance WHERE id = :id");
                $stmt->execute(['credit_balance' => $new_credit_balance, 'id' => $clientId]);

                // Log the transaction
                $logStmt = $db->prepare("INSERT INTO client_credit_log (client_id, amount, transaction_type, notes) VALUES (:client_id, :amount, :transaction_type, :notes)");
                $logStmt->execute([
                    'client_id' => $clientId,
                    'amount' => $payback_amount,
                    'transaction_type' => 'payment',
                    'notes' => 'Credit payback'
                ]);

                $successMessage = 'Spłata kredytu została pomyślnie przetworzona.';
                
                // 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);
                $available_credit = $client['credit_balance'];
                $used_credit = $client['credit_limit'] - $client['credit_balance'];

            } catch (PDOException $e) {
                $errorMessage = 'Wystąpił błąd podczas przetwarzania spłaty kredytu.';
                // error_log($e->getMessage()); // Uncomment for debugging
            }
        }
    } elseif (isset($_POST['cancel_payment']) && isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin') {
        $log_id = $_POST['log_id'] ?? null;
        if ($log_id) {
            $db->beginTransaction();
            try {
                // Get the payment amount from the log
                $logStmt = $db->prepare("SELECT * FROM client_credit_log WHERE id = :id AND client_id = :client_id");
                $logStmt->execute(['id' => $log_id, 'client_id' => $clientId]);
                $logEntry = $logStmt->fetch(PDO::FETCH_ASSOC);

                if ($logEntry && $logEntry['transaction_type'] === 'payment') {
                    // Revert the credit balance
                    $new_credit_balance = $client['credit_balance'] - $logEntry['amount'];
                    
                    $updateStmt = $db->prepare("UPDATE clients SET credit_balance = :credit_balance WHERE id = :id");
                    $updateStmt->execute(['credit_balance' => $new_credit_balance, 'id' => $clientId]);

                    // Delete the log entry
                    $deleteStmt = $db->prepare("DELETE FROM client_credit_log WHERE id = :id");
                    $deleteStmt->execute(['id' => $log_id]);
                    
                    $db->commit();
                    $successMessage = "Płatność została pomyślnie anulowana.";

                    // Re-fetch client data
                    $stmt = $db->prepare("SELECT * FROM clients WHERE id = :id");
                    $stmt->execute(['id' => $clientId]);
                    $client = $stmt->fetch(PDO::FETCH_ASSOC);
                    $available_credit = $client['credit_balance'];
                    $used_credit = $client['credit_limit'] - $client['credit_balance'];
                } else {
                    $db->rollBack();
                    $errorMessage = "Nie znaleziono wpisu płatności lub transakcja nie jest płatnością.";
                }
            } catch (PDOException $e) {
                $db->rollBack();
                $errorMessage = "Wystąpił błąd podczas anulowania płatności.";
                // error_log($e->getMessage()); // For debugging
            }
        }
    } else {
        // Main form submission for creating/updating the client
        $name = $_POST['name'] ?? '';
        $tax_id = $_POST['tax_id'] ?? '';
        $address = $_POST['address'] ?? '';
        $city = $_POST['city'] ?? '';
        $zip_code = $_POST['zip_code'] ?? '';
        $language = $_POST['language'] ?? 'pl';

        if (empty($name)) {
            $errorMessage = 'Nazwa klienta jest wymagana.';
        } else {
            try {
                if ($isNewClient) {
                    $credit_limit = (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin') ? ($_POST['credit_limit'] ?? 0) : 0;
                    $stmt = $db->prepare("INSERT INTO clients (name, nip, street, city, postal_code, language, credit_limit, credit_balance) VALUES (:name, :tax_id, :address, :city, :zip_code, :language, :credit_limit, :credit_limit)");
                    $params = [
                        'name' => $name,
                        'tax_id' => $tax_id,
                        'address' => $address,
                        'city' => $city,
                        'zip_code' => $zip_code,
                        'language' => $language,
                        'credit_limit' => $credit_limit
                    ];
                } else {
                    if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin') {
                        $credit_limit = $_POST['credit_limit'] ?? $client['credit_limit'];
                        $stmt = $db->prepare("UPDATE clients SET name = :name, nip = :tax_id, street = :address, city = :city, postal_code = :zip_code, language = :language, credit_limit = :credit_limit WHERE id = :id");
                        $params = [
                            'name' => $name,
                            'tax_id' => $tax_id,
                            'address' => $address,
                            'city' => $city,
                            'zip_code' => $zip_code,
                            'language' => $language,
                            'credit_limit' => $credit_limit,
                            'id' => $clientId
                        ];
                    } else {
                        $stmt = $db->prepare("UPDATE clients SET name = :name, nip = :tax_id, street = :address, city = :city, postal_code = :zip_code, language = :language WHERE id = :id");
                        $params = [
                            'name' => $name,
                            'tax_id' => $tax_id,
                            'address' => $address,
                            'city' => $city,
                            'zip_code' => $zip_code,
                            'language' => $language,
                            '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);
                $available_credit = $client['credit_balance'];
                $used_credit = $client['credit_limit'] - $client['credit_balance'];

            } catch (PDOException $e) {
                $errorMessage = 'Wystąpił błąd podczas zapisywania danych klienta: ';// . $e->getMessage();
                // error_log($e->getMessage()); // Uncomment for debugging
            }
        }
    }
}
$page_title = $pageTitle;
?>
<?php require_once __DIR__ . '/../includes/html_head.php'; ?>
<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="language" class="form-label">Język</label>
                    <select class="form-control" id="language" name="language">
                        <option value="pl" <?php echo (($client['language'] ?? 'pl') === 'pl') ? 'selected' : ''; ?>>Polski</option>
                        <option value="en" <?php echo (($client['language'] ?? '') === 'en') ? 'selected' : ''; ?>>Angielski</option>
                    </select>
                </div>
                <?php if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin'): ?>
                <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 ($available_credit < 0) ? 'text-danger' : 'text-success'; ?>">
                        <?php echo number_format($available_credit, 2, ',', ' '); ?> PLN
                    </p>
                </div>
                <?php endif; ?>
                <?php endif; ?>
                <button type="submit" class="btn btn-primary">Zapisz</button>
                <a href="clients.php" class="btn btn-secondary">Anuluj</a>
            </form>
            <?php if ($clientId && isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin'): ?>
            <hr>
            <h5 class="mt-4">Spłata kredytu</h5>
            <form method="post" class="mt-3">
                <div class="mb-3">
                    <label for="payback_amount" class="form-label">Kwota spłaty</label>
                    <input type="number" step="0.01" class="form-control" id="payback_amount" name="payback_amount" required>
                </div>
                <button type="submit" class="btn btn-success" name="payback_submit">Zatwierdź spłatę</button>
            </form>
            
            <hr>
            <h5 class="mt-4">Historia kredytu</h5>
            <?php
            $logStmt = $db->prepare("SELECT * FROM client_credit_log WHERE client_id = :client_id ORDER BY created_at DESC");
            $logStmt->execute(['client_id' => $clientId]);
            $creditLogs = $logStmt->fetchAll(PDO::FETCH_ASSOC);
            ?>
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Data</th>
                        <th>Typ</th>
                        <th>Kwota</th>
                        <th>Notatki</th>
                        <th>Akcje</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($creditLogs as $log): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($log['created_at']); ?></td>
                            <td><?php echo htmlspecialchars($log['transaction_type']); ?></td>
                            <td><?php echo number_format($log['amount'], 2, ',', ' '); ?> PLN</td>
                            <td><?php echo htmlspecialchars($log['notes']); ?></td>
                            <td>
                                <?php if ($log['transaction_type'] === 'payment'): ?>
                                <form method="post" onsubmit="return confirm('Czy na pewno chcesz anulować tę płatność?');" style="display: inline;">
                                    <input type="hidden" name="log_id" value="<?php echo $log['id']; ?>">
                                    <button type="submit" name="cancel_payment" class="btn btn-danger btn-sm">Anuluj</button>
                                </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if (empty($creditLogs)): ?>
                        <tr>
                            <td colspan="5" class="text-center">Brak historii kredytowej.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
</body>
</html>
