<?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();
$payment_type = $_GET['type'] ?? 'Genel';

$recipients = []; // Ödeme yapılacak alıcılar
$payments = []; // Yapılan son ödemeler
$is_tasaron = ($payment_type === 'Tasaron');
$page_title = $is_tasaron ? 'Taşeron Ödemeleri' : 'Malzeme Ödemeleri';

// Ödeme kaydetme işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_payment') {
    $payment_date = $_POST['payment_date'] ?? date('Y-m-d');
    $amount = $_POST['amount'] ?? 0;
    $recipient_id = $_POST['recipient_id'] ?? 0;
    $notes = $_POST['notes'] ?? '';
    $recipient_name = $_POST['recipient_name'] ?? '';
    $payment_type_post = $_POST['payment_type_post'] ?? 'Genel';
    
    // Proje ID'si zorunlu değilse null kalabilir
    $project_id = $_POST['project_id'] ?? null;
    
    try {
        $stmt = $conn->prepare("INSERT INTO finance_payments (payment_date, type, amount, recipient, description, project_id, user_id) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$payment_date, $payment_type_post, $amount, $recipient_name, $notes, $project_id, $_SESSION['user_id']]);
        
        $message = $payment_type_post . ' ödemesi başarıyla kaydedildi!';
        $message_type = 'success';
        header("Location: payments.php?type=$payment_type_post&status=$message_type&message=" . urlencode($message));
        exit;
    } catch (PDOException $e) {
        $message = 'Hata: Ödeme kaydedilirken bir sorun oluştu. ' . $e->getMessage();
        $message_type = 'error';
        header("Location: payments.php?type=$payment_type_post&status=$message_type&message=" . urlencode($message));
        exit;
    }
}

// Veri çekme
try {
    // 1. Alıcı Listesini Çekme
    if ($is_tasaron) {
        $stmt_recipients = $conn->prepare("SELECT id, subcontractor_name AS name FROM subcontractors ORDER BY name ASC");
    } else {
        $stmt_recipients = $conn->prepare("SELECT id, supplier_name AS name FROM suppliers ORDER BY name ASC");
    }
    $stmt_recipients->execute();
    $recipients = $stmt_recipients->fetchAll(PDO::FETCH_ASSOC);
    
    // 2. Proje Listesini Çekme
    $stmt_projects = $conn->prepare("SELECT id, project_name FROM projects ORDER BY project_name ASC");
    $stmt_projects->execute();
    $projects = $stmt_projects->fetchAll(PDO::FETCH_ASSOC);

    // 3. Yapılan Son Ödemeleri Çekme
    $stmt_payments = $conn->prepare("SELECT fp.*, u.name as user_name FROM finance_payments fp JOIN users u ON fp.user_id = u.id WHERE fp.type = ? ORDER BY fp.payment_date DESC LIMIT 10");
    $stmt_payments->execute([$payment_type]);
    $payments = $stmt_payments->fetchAll(PDO::FETCH_ASSOC);

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

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Hati App - <?php echo htmlspecialchars($page_title); ?></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><?php echo htmlspecialchars($page_title); ?></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 Ödeme Kaydı</h3>
    <form action="payments.php" method="POST">
        <input type="hidden" name="action" value="add_payment">
        <input type="hidden" name="payment_type_post" value="<?php echo htmlspecialchars($payment_type); ?>">
        
        <div class="form-grid">
            <div class="form-group">
                <label for="recipient_id"><?php echo $is_tasaron ? 'Taşeron Firma Seçin' : 'Tedarikçi Firma Seçin'; ?>:</label>
                <select id="recipient_id" name="recipient_id" required onchange="document.getElementById('recipient_name_input').value = this.options[this.selectedIndex].text;">
                    <option value="">Seçiniz</option>
                    <?php foreach ($recipients as $rec): ?>
                        <option value="<?php echo $rec['id']; ?>"><?php echo htmlspecialchars($rec['name']); ?></option>
                    <?php endforeach; ?>
                </select>
                <input type="hidden" id="recipient_name_input" name="recipient_name">
            </div>
            
            <div class="form-group">
                <label for="amount">Ödeme Tutarı (TL):</label>
                <input type="number" id="amount" name="amount" step="0.01" min="0" required>
            </div>
            
            <div class="form-group">
                <label for="payment_date">Ödeme Tarihi:</label>
                <input type="date" id="payment_date" name="payment_date" value="<?php echo date('Y-m-d'); ?>" required>
            </div>

            <div class="form-group">
                <label for="project_id">İlgili Proje (Opsiyonel):</label>
                <select id="project_id" name="project_id">
                    <option value="">Seçiniz</option>
                    <?php foreach ($projects as $proj): ?>
                        <option value="<?php echo $proj['id']; ?>"><?php echo htmlspecialchars($proj['project_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        
        <div class="form-group full-width">
            <label for="notes">Notlar/Açıklama:</label>
            <textarea id="notes" name="notes" rows="3"></textarea>
        </div>
        
        <div class="form-actions">
            <button type="submit">Ödeme Yap</button>
        </div>
    </form>
</div>

<div class="detail-box" style="margin-top: 2rem;">
    <h3 class="detail-box-title">Son Yapılan Ödemeler (<?php echo htmlspecialchars($page_title); ?>)</h3>
    <?php if (empty($payments)): ?>
        <p>Henüz <?php echo strtolower($page_title); ?> kaydı bulunmamaktadır.</p>
    <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>Alıcı</th>
                    <th>Tutar</th>
                    <th>Tarih</th>
                    <th>Açıklama</th>
                    <th>Kayıt Eden</th>
                    <th>İşlemler</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($payments as $pay): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($pay['recipient']); ?></td>
                        <td><?php echo number_format($pay['amount'], 2, ',', '.'); ?> TL</td>
                        <td><?php echo htmlspecialchars($pay['payment_date']); ?></td>
                        <td><?php echo htmlspecialchars($pay['description'] ?? '-'); ?></td>
                        <td><?php echo htmlspecialchars($pay['user_name']); ?></td>
                        <td>
                            <a href="delete.php?table=finance_payments&id=<?php echo $pay['id']; ?>&redirect=payments.php?type=<?php echo $payment_type; ?>" class="btn-danger" onclick="return confirm('Bu ödeme kaydını silmek istediğinizden emin misiniz?');">Sil</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

</body>
</html>