<?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;
$db = new Database();
$conn = $db->getConnection();
$payments = [];
$contracts = [];
$message = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';
try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $contract_id = $_POST['contract_id'] ?? null;
        $amount = $_POST['amount'] ?? 0;
        $notes = $_POST['notes'] ?? '';
        $payment_date = $_POST['payment_date'] ?? date('Y-m-d');
        $progress_no = 'HKDŞ-' . date('Y') . '-' . uniqid();
        $stmt = $conn->prepare("INSERT INTO technical_office_progress_payments (progress_no, contract_id, amount, payment_date, notes) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$progress_no, $contract_id, $amount, $payment_date, $notes]);
        $message = 'Yeni hakediş kaydı başarıyla oluşturuldu!';
        $message_type = 'success';
    }
    $stmt_list = $conn->prepare("SELECT tpp.*, tc.contract_no FROM technical_office_progress_payments tpp JOIN technical_office_contracts tc ON tpp.contract_id = tc.id ORDER BY tpp.payment_date DESC");
    $stmt_list->execute();
    $payments = $stmt_list->fetchAll(PDO::FETCH_ASSOC);
    $stmt_contracts = $conn->prepare("SELECT id, contract_no FROM technical_office_contracts ORDER BY contract_no DESC");
    $stmt_contracts->execute();
    $contracts = $stmt_contracts->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $message = "Hata: " . $e->getMessage();
    $message_type = 'error';
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Hati App - Hakedişler</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<?php require_once __DIR__ . '/../src/Includes/header.php'; ?>
<div class="header-actions">
    <h2>Hakedişler</h2>
    <a href="#new-payment">Yeni Hakediş Ekle</a>
</div>
<?php if ($message): ?>
    <p style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;"><?php echo htmlspecialchars($message); ?></p>
<?php endif; ?>
<h3>Mevcut Hakedişler</h3>
<?php if (empty($payments)): ?>
    <p>Henüz kayıtlı bir hakediş bulunmamaktadır.</p>
<?php else: ?>
    <table>
        <thead>
            <tr>
                <th>Hakediş No</th>
                <th>İlgili Sözleşme</th>
                <th>Tarih</th>
                <th>Tutar</th>
                <th>Durum</th>
                <th>İşlemler</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($payments as $payment): ?>
                <tr>
                    <td><?php echo htmlspecialchars($payment['progress_no']); ?></td>
                    <td><?php echo htmlspecialchars($payment['contract_no']); ?></td>
                    <td><?php echo htmlspecialchars($payment['payment_date']); ?></td>
                    <td><?php echo number_format($payment['amount'], 2, ',', '.'); ?> TL</td>
                    <td>
                        <?php 
                        $statusInfo = getStatusInfo($payment['status']); 
                        ?>
                        <span class="status <?php echo $statusInfo['class']; ?>"><?php echo $statusInfo['label']; ?></span>
                    </td>
                    <td>
                        <a href="view_payment.php?id=<?php echo $payment['id']; ?>">Gör</a> |
                        <a href="delete.php?table=technical_office_progress_payments&id=<?php echo $payment['id']; ?>&redirect=progress_payments.php" onclick="return confirm('Bu kaydı silmek istediğinizden emin misiniz?');">Sil</a>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>
<hr>
<h3 id="new-payment">Yeni Hakediş Ekle</h3>
<form action="progress_payments.php" method="POST">
    <div class="form-section-title">Genel Bilgiler</div>
    <div class="form-grid">
        <div class="form-group">
            <label for="contract_id">İlgili Sözleşme:</label>
            <select id="contract_id" name="contract_id" required>
                <?php foreach ($contracts as $contract): ?>
                    <option value="<?php echo $contract['id']; ?>"><?php echo htmlspecialchars($contract['contract_no']); ?></option>
                <?php endforeach; ?>
            </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="payment_date">Tarih:</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="5"></textarea>
    </div>
    <div class="form-actions full-width">
        <button type="submit">Hakedişi Kaydet</button>
    </div>
</form>
</main>
</body>
</html>