<?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();
$calendar_entries = [];

// Takvim kaydı ekleme işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_calendar_entry') {
    $title = $_POST['title'] ?? '';
    $date = $_POST['date'] ?? date('Y-m-d');
    $amount = $_POST['amount'] ?? 0;
    $type = $_POST['type'] ?? 'Odeme';
    $notes = $_POST['notes'] ?? '';

    try {
        $stmt = $conn->prepare("INSERT INTO finance_payment_calendar (title, date, amount, type, notes, user_id) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$title, $date, $amount, $type, $notes, $_SESSION['user_id']]);
        
        $message = 'Yeni ödeme takvimi kaydı başarıyla eklendi!';
        $message_type = 'success';
        header("Location: payment_calendar.php?status=success&message=" . urlencode($message));
        exit;
    } catch (PDOException $e) {
        $message = 'Hata: Kayıt eklenirken bir sorun oluştu. ' . $e->getMessage();
        $message_type = 'error';
        header("Location: payment_calendar.php?status=error&message=" . urlencode($message));
        exit;
    }
}

// Mevcut takvim kayıtlarını çekme
try {
    $stmt_calendar = $conn->prepare("SELECT fpc.*, u.name as user_name FROM finance_payment_calendar fpc JOIN users u ON fpc.user_id = u.id ORDER BY fpc.date ASC");
    $stmt_calendar->execute();
    $calendar_entries = $stmt_calendar->fetchAll(PDO::FETCH_ASSOC);

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

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Hati App - Ödeme Takvimi</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>Ödeme ve Tahsilat Takvimi</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 Takvim Kaydı Ekle</h3>
    <form action="payment_calendar.php" method="POST">
        <input type="hidden" name="action" value="add_calendar_entry">
        
        <div class="form-grid">
            <div class="form-group">
                <label for="title">Başlık (Örn: Kira Ödemesi, Müşteri Tahsilat)</label>
                <input type="text" id="title" name="title" required>
            </div>
            <div class="form-group">
                <label for="type">İşlem Türü:</label>
                <select id="type" name="type" required>
                    <option value="Odeme">Ödeme (Gider)</option>
                    <option value="Tahsilat">Tahsilat (Gelir)</option>
                </select>
            </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="date">Vade / İşlem Tarihi:</label>
                <input type="date" id="date" name="date" required>
            </div>
        </div>
        
        <div class="form-group full-width">
            <label for="notes">Notlar:</label>
            <textarea id="notes" name="notes" rows="2"></textarea>
        </div>
        
        <div class="form-actions">
            <button type="submit">Takvime Ekle</button>
        </div>
    </form>
</div>

<div class="detail-box" style="margin-top: 2rem;">
    <h3 class="detail-box-title">Yaklaşan İşlemler</h3>
    <?php if (empty($calendar_entries)): ?>
        <p>Ödeme veya tahsilat takvimi kaydı bulunmamaktadır.</p>
    <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>Tarih</th>
                    <th>Başlık</th>
                    <th>Tutar</th>
                    <th>Tür</th>
                    <th>Durum</th>
                    <th>İşlemler</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($calendar_entries as $entry): ?>
                    <?php 
                    $is_overdue = strtotime($entry['date']) < time() && $entry['is_completed'] == 0;
                    $status_label = $entry['is_completed'] ? 'Tamamlandı' : ($is_overdue ? 'Vadesi Geçti' : 'Beklemede');
                    $status_class = $entry['is_completed'] ? 'status-success' : ($is_overdue ? 'status-red' : 'status-pending');
                    ?>
                    <tr>
                        <td><?php echo htmlspecialchars($entry['date']); ?></td>
                        <td><?php echo htmlspecialchars($entry['title']); ?></td>
                        <td><?php echo number_format($entry['amount'], 2, ',', '.'); ?> TL</td>
                        <td><?php echo htmlspecialchars($entry['type']); ?></td>
                        <td>
                            <span class="status <?php echo $status_class; ?>"><?php echo $status_label; ?></span>
                        </td>
                        <td>
                            <a href="delete.php?table=finance_payment_calendar&id=<?php echo $entry['id']; ?>&redirect=payment_calendar.php" class="btn-danger" onclick="return confirm('Bu kaydı silmek istediğinizden emin misiniz?');">Sil</a>
                            </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

</body>
</html>