<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: login.php');
    exit;
}
require_once __DIR__ . '/../src/Core/Database.php';
require_once __DIR__ . '/../src/Includes/helpers.php';
use HatiApp\Core\Database;

$message = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';
$db = new Database();
$conn = $db->getConnection();
$checks = [];

// Çek ekleme işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_check') {
    $check_number = $_POST['check_number'] ?? '';
    $check_date = $_POST['check_date'] ?? date('Y-m-d');
    $due_date = $_POST['due_date'] ?? date('Y-m-d');
    $amount = $_POST['amount'] ?? 0;
    $recipient = $_POST['recipient'] ?? 'Bilinmiyor';
    $description = $_POST['description'] ?? '';
    
    try {
        $stmt = $conn->prepare("INSERT INTO finance_checks (check_number, check_date, due_date, amount, recipient, description, user_id) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$check_number, $check_date, $due_date, $amount, $recipient, $description, $_SESSION['user_id']]);
        
        $message = 'Yeni çek başarıyla kaydedildi!';
        $message_type = 'success';
        header("Location: checks.php?status=success&message=" . urlencode($message));
        exit;
    } catch (PDOException $e) {
        $message = 'Hata: Çek kaydedilirken bir sorun oluştu. ' . $e->getMessage();
        $message_type = 'error';
        header("Location: checks.php?status=error&message=" . urlencode($message));
        exit;
    }
}

// Mevcut çekleri çekme
try {
    $stmt_checks = $conn->prepare("SELECT fc.*, u.name as user_name FROM finance_checks fc JOIN users u ON fc.user_id = u.id ORDER BY fc.due_date ASC");
    $stmt_checks->execute();
    $checks = $stmt_checks->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Hata: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Hati App - Çek Takibi</title>
    <link rel="stylesheet" href="css/style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?php require_once __DIR__ . '/../src/Includes/header.php'; ?>
<div class="header-actions">
    <h2>Çek Takibi</h2>
    <a href="muhasebe.php" class="secondary-btn">Geri Dön</a>
</div>
<?php if ($message): ?>
    <p class="message" style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
        <?php echo htmlspecialchars($message); ?>
    </p>
<?php endif; ?>

<div class="detail-box">
    <h3 class="detail-box-title">Yeni Çek Kaydı</h3>
    <form action="checks.php" method="POST">
        <input type="hidden" name="action" value="add_check">
        
        <div class="form-grid">
            <div class="form-group">
                <label for="check_number">Çek Numarası:</label>
                <input type="text" id="check_number" name="check_number" required>
            </div>
            <div class="form-group">
                <label for="recipient">Alıcı (Kime Verildi?):</label>
                <input type="text" id="recipient" name="recipient" required>
            </div>
            <div class="form-group">
                <label for="amount">Tutar (TL):</label>
                <input type="number" id="amount" name="amount" step="0.01" min="0" required>
            </div>
            <div class="form-group">
                <label for="due_date">Vade Tarihi:</label>
                <input type="date" id="due_date" name="due_date" required>
            </div>
            <div class="form-group">
                <label for="check_date">Düzenleme Tarihi:</label>
                <input type="date" id="check_date" name="check_date" value="<?php echo date('Y-m-d'); ?>" required>
            </div>
        </div>
        
        <div class="form-group full-width">
            <label for="description">Notlar:</label>
            <textarea id="description" name="description" rows="2"></textarea>
        </div>
        
        <div class="form-actions">
            <button type="submit">Çek Kaydet</button>
        </div>
    </form>
</div>

<div class="detail-box" style="margin-top: 2rem;">
    <h3 class="detail-box-title">Mevcut Çekler (Vadeye Göre Sıralı)</h3>
    <?php if (empty($checks)): ?>
        <p>Henüz kayıtlı çek bulunmamaktadır.</p>
    <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>Çek No</th>
                    <th>Alıcı</th>
                    <th>Tutar</th>
                    <th>Vade Tarihi</th>
                    <th>Durum</th>
                    <th>İşlemler</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($checks as $check): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($check['check_number']); ?></td>
                        <td><?php echo htmlspecialchars($check['recipient']); ?></td>
                        <td><?php echo number_format($check['amount'], 2, ',', '.'); ?> TL</td>
                        <td><?php echo htmlspecialchars($check['due_date']); ?></td>
                        <td>
                            <?php 
                            // Vade tarihi kontrolü
                            $is_due = strtotime($check['due_date']) < time() && $check['status'] === 'Duzenlendi';
                            $status = $is_due ? 'Vadesi Geçti' : $check['status'];
                            $statusClass = getStatusInfo(strtolower(str_replace(' ', '_', $status)))['class'];
                            ?>
                            <span class="status <?php echo $statusClass; ?>"><?php echo htmlspecialchars($status); ?></span>
                        </td>
                        <td>
                            <a href="delete.php?table=finance_checks&id=<?php echo $check['id']; ?>&redirect=checks.php" class="btn-danger" onclick="return confirm('Bu çeki silmek istediğinizden emin misiniz?');">Sil</a>
                            </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

</body>
</html>