<?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();
$contracts = [];
$projects = [];
$message = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';
try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $customer_name = $_POST['customer_name'] ?? '';
        $contract_date = $_POST['contract_date'] ?? date('Y-m-d');
        $contract_price = $_POST['contract_price'] ?? 0;
        $project_id = $_POST['project_id'] ?? null;
        $payment_terms = $_POST['payment_terms'] ?? '';
        $notes = $_POST['notes'] ?? '';
        $contract_no = 'SÖZ-' . date('Y') . '-' . uniqid();
        $created_by_user_id = $_SESSION['user_id'];
        $stmt = $conn->prepare("INSERT INTO technical_office_contracts (contract_no, project_id, customer_name, contract_date, contract_price, payment_terms, notes, created_by_user_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$contract_no, $project_id, $customer_name, $contract_date, $contract_price, $payment_terms, $notes, $created_by_user_id]);
        $message = 'Yeni sözleşme kaydı başarıyla oluşturuldu!';
        $message_type = 'success';
    }
    $stmt_list = $conn->prepare("SELECT tc.*, p.project_name FROM technical_office_contracts tc LEFT JOIN projects p ON tc.project_id = p.id ORDER BY tc.contract_date DESC");
    $stmt_list->execute();
    $contracts = $stmt_list->fetchAll(PDO::FETCH_ASSOC);
    $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);
} catch (PDOException $e) {
    $message = "Hata: " . $e->getMessage();
    $message_type = 'error';
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Hati App - Sözleşmeler</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<?php require_once __DIR__ . '/../src/Includes/header.php'; ?>
<div class="header-actions">
    <h2>Sözleşmeler</h2>
    <a href="#new-contract">Yeni Sözleşme 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 Sözleşmeler</h3>
<?php if (empty($contracts)): ?>
    <p>Henüz kayıtlı bir sözleşme bulunmamaktadır.</p>
<?php else: ?>
    <table>
        <thead>
            <tr>
                <th>Sözleşme No</th>
                <th>Müşteri Adı</th>
                <th>Sözleşme Tarihi</th>
                <th>Bedeli</th>
                <th>İlgili Proje</th>
                <th>İşlemler</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($contracts as $contract): ?>
                <tr>
                    <td><?php echo htmlspecialchars($contract['contract_no']); ?></td>
                    <td><?php echo htmlspecialchars($contract['customer_name']); ?></td>
                    <td><?php echo htmlspecialchars($contract['contract_date']); ?></td>
                    <td><?php echo number_format($contract['contract_price'], 2, ',', '.'); ?> TL</td>
                    <td><?php echo htmlspecialchars($contract['project_name'] ?? '-'); ?></td>
                    <td><a href="view_contract.php?id=<?php echo $contract['id']; ?>">Detaylar</a> | <a href="delete.php?table=technical_office_contracts&id=<?php echo $contract['id']; ?>&redirect=contracts.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-contract">Yeni Sözleşme Ekle</h3>
<form action="contracts.php" method="POST">
    <div class="form-section-title">Genel Bilgiler</div>
    <div class="form-grid">
        <div class="form-group">
            <label for="customer_name">Müşteri Adı:</label>
            <input type="text" id="customer_name" name="customer_name" required>
        </div>
        <div class="form-group">
            <label for="contract_date">Sözleşme Tarihi:</label>
            <input type="date" id="contract_date" name="contract_date" value="<?php echo date('Y-m-d'); ?>" required>
        </div>
        <div class="form-group">
            <label for="contract_price">Sözleşme Bedeli (TL):</label>
            <input type="number" id="contract_price" name="contract_price" step="0.01" min="0" required>
        </div>
        <div class="form-group">
            <label for="project_id">İlgili Proje:</label>
            <select id="project_id" name="project_id">
                <option value="">İlişkilendirme Yok</option>
                <?php foreach ($projects as $project): ?>
                    <option value="<?php echo $project['id']; ?>"><?php echo htmlspecialchars($project['project_name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>
    <div class="form-group full-width">
        <label for="payment_terms">Ödeme Koşulları:</label>
        <textarea id="payment_terms" name="payment_terms" rows="3"></textarea>
    </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">Sözleşmeyi Kaydet</button>
    </div>
</form>
</main>
</body>
</html>