<?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();
$personnel = [];
$suppliers = [];
$personnel_payments = [];
$supplier_payments = [];

// Ödeme işlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'personnel_payment') {
        $personnel_id = $_POST['personnel_id'] ?? 0;
        $amount = $_POST['amount'] ?? 0;
        $payment_date = $_POST['payment_date'] ?? date('Y-m-d');
        $notes = $_POST['notes'] ?? '';
        try {
            $stmt = $conn->prepare("INSERT INTO personnel_payments (personnel_id, amount, payment_date, notes) VALUES (?, ?, ?, ?)");
            $stmt->execute([$personnel_id, $amount, $payment_date, $notes]);
            $message = 'Personel ödemesi başarıyla yapıldı.';
            $message_type = 'success';
        } catch (PDOException $e) {
            $message = 'Hata: Ödeme yapılırken bir sorun oluştu. ' . $e->getMessage();
            $message_type = 'error';
        }
    } elseif ($_POST['action'] === 'supplier_payment') {
        $supplier_id = $_POST['supplier_id'] ?? 0;
        $amount = $_POST['amount'] ?? 0;
        $payment_date = $_POST['payment_date'] ?? date('Y-m-d');
        $notes = $_POST['notes'] ?? '';
        try {
            $stmt = $conn->prepare("INSERT INTO supplier_payments (supplier_id, amount, payment_date, notes) VALUES (?, ?, ?, ?)");
            $stmt->execute([$supplier_id, $amount, $payment_date, $notes]);
            $message = 'Tedarikçi ödemesi başarıyla yapıldı.';
            $message_type = 'success';
        } catch (PDOException $e) {
            $message = 'Hata: Ödeme yapılırken bir sorun oluştu. ' . $e->getMessage();
            $message_type = 'error';
        }
    }
    header("Location: odemeler.php?status=$message_type&message=" . urlencode($message));
    exit;
}

// Personel, tedarikçi ve ödeme verilerini çekme
try {
    $stmt_personnel = $conn->prepare("SELECT id, full_name, salary FROM personnel ORDER BY full_name ASC");
    $stmt_personnel->execute();
    $personnel = $stmt_personnel->fetchAll(PDO::FETCH_ASSOC);

    $stmt_suppliers = $conn->prepare("SELECT id, supplier_name FROM suppliers ORDER BY supplier_name ASC");
    $stmt_suppliers->execute();
    $suppliers = $stmt_suppliers->fetchAll(PDO::FETCH_ASSOC);

    // Personel ödemelerini listeleme
    $stmt_personnel_payments = $conn->prepare("SELECT pp.*, p.full_name FROM personnel_payments pp JOIN personnel p ON pp.personnel_id = p.id ORDER BY pp.payment_date DESC LIMIT 10");
    $stmt_personnel_payments->execute();
    $personnel_payments = $stmt_personnel_payments->fetchAll(PDO::FETCH_ASSOC);

    // Tedarikçi ödemelerini listeleme
    $stmt_supplier_payments = $conn->prepare("SELECT sp.*, s.supplier_name FROM supplier_payments sp JOIN suppliers s ON sp.supplier_id = s.id ORDER BY sp.payment_date DESC LIMIT 10");
    $stmt_supplier_payments->execute();
    $supplier_payments = $stmt_supplier_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 - Ödemeler</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>Ödemeler</h2>
    <a href="personel.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-grid">
    <div class="detail-box">
        <h3 class="detail-box-title">Personel Ödemeleri</h3>
        <form action="odemeler.php" method="POST">
            <input type="hidden" name="action" value="personnel_payment">
            <div class="form-grid">
                <div class="form-group">
                    <label for="personnel_id">Personel Seç:</label>
                    <select id="personnel_id" name="personnel_id" required>
                        <option value="">Seçiniz</option>
                        <?php foreach ($personnel as $p): ?>
                            <option value="<?php echo $p['id']; ?>"><?php echo htmlspecialchars($p['full_name']); ?> (Maaş: <?php echo number_format($p['salary'], 2, ',', '.'); ?> TL)</option>
                        <?php endforeach; ?>
                    </select>
                </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>
            <div class="form-group full-width">
                <label for="notes">Notlar:</label>
                <textarea id="notes" name="notes" rows="3"></textarea>
            </div>
            <div class="form-actions">
                <button type="submit">Ödeme Yap</button>
            </div>
        </form>
        <hr>
        <h4>Son Yapılan Ödemeler</h4>
        <?php if (empty($personnel_payments)): ?>
            <p>Henüz personel ödemesi yapılmamıştır.</p>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>Personel</th>
                        <th>Tutar</th>
                        <th>Tarih</th>
                        <th>Notlar</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($personnel_payments as $payment): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($payment['full_name']); ?></td>
                            <td><?php echo number_format($payment['amount'], 2, ',', '.'); ?> TL</td>
                            <td><?php echo htmlspecialchars($payment['payment_date']); ?></td>
                            <td><?php echo htmlspecialchars($payment['notes']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <div class="detail-box">
        <h3 class="detail-box-title">Tedarikçi Ödemeleri</h3>
        <form action="odemeler.php" method="POST">
            <input type="hidden" name="action" value="supplier_payment">
            <div class="form-grid">
                <div class="form-group">
                    <label for="supplier_id">Tedarikçi Firma:</label>
                    <select id="supplier_id" name="supplier_id" required>
                        <option value="">Seçiniz</option>
                        <?php foreach ($suppliers as $s): ?>
                            <option value="<?php echo $s['id']; ?>"><?php echo htmlspecialchars($s['supplier_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="amount_supplier">Ödeme Tutarı (TL):</label>
                    <input type="number" id="amount_supplier" name="amount" step="0.01" min="0" required>
                </div>
                <div class="form-group">
                    <label for="payment_date_supplier">Ödeme Tarihi:</label>
                    <input type="date" id="payment_date_supplier" name="payment_date" value="<?php echo date('Y-m-d'); ?>" required>
                </div>
            </div>
            <div class="form-group full-width">
                <label for="notes_supplier">Notlar:</label>
                <textarea id="notes_supplier" name="notes" rows="3"></textarea>
            </div>
            <div class="form-actions">
                <button type="submit">Ödeme Yap</button>
            </div>
        </form>
        <hr>
        <h4>Son Yapılan Ödemeler</h4>
        <?php if (empty($supplier_payments)): ?>
            <p>Henüz tedarikçi ödemesi yapılmamıştır.</p>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>Tedarikçi</th>
                        <th>Tutar</th>
                        <th>Tarih</th>
                        <th>Notlar</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($supplier_payments as $payment): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($payment['supplier_name']); ?></td>
                            <td><?php echo number_format($payment['amount'], 2, ',', '.'); ?> TL</td>
                            <td><?php echo htmlspecialchars($payment['payment_date']); ?></td>
                            <td><?php echo htmlspecialchars($payment['notes']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>
</body>
</html>