<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    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();
$offers = [];
$message = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';

// Dashboard için veri çekme
$stats = [
    'draft_offers' => 0,
    'sent_offers' => 0,
    'accepted_offers' => 0,
    'rejected_offers' => 0,
    'total_offers' => 0
];
try {
    $stmt_draft = $conn->query("SELECT COUNT(*) FROM offers WHERE status = 'draft'");
    $stats['draft_offers'] = $stmt_draft->fetchColumn();
    $stmt_sent = $conn->query("SELECT COUNT(*) FROM offers WHERE status = 'sent'");
    $stats['sent_offers'] = $stmt_sent->fetchColumn();
    $stmt_accepted = $conn->query("SELECT COUNT(*) FROM offers WHERE status = 'accepted'");
    $stats['accepted_offers'] = $stmt_accepted->fetchColumn();
    $stmt_rejected = $conn->query("SELECT COUNT(*) FROM offers WHERE status = 'rejected'");
    $stats['rejected_offers'] = $stmt_rejected->fetchColumn();
    $stmt_total = $conn->query("SELECT COUNT(*) FROM offers");
    $stats['total_offers'] = $stmt_total->fetchColumn();
    
    $stmt = $conn->prepare("SELECT o.*, p.project_name FROM offers o LEFT JOIN projects p ON o.project_id = p.id ORDER BY o.offer_date DESC");
    $stmt->execute();
    $offers = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo "Hata: " . $e->getMessage();
}

// Teklif durumunu güncelleme işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_status') {
    $offer_id = $_POST['offer_id'] ?? 0;
    $new_status = $_POST['new_status'] ?? null;
    
    if ($offer_id > 0 && $new_status) {
        try {
            $stmt = $conn->prepare("UPDATE offers SET status = ? WHERE id = ?");
            $stmt->execute([$new_status, $offer_id]);
            
            if ($new_status === 'accepted') {
                header("Location: create_project.php?offer_id=$offer_id");
                exit;
            }
            
            header("Location: offers.php?status=success&message=" . urlencode('Teklif durumu güncellendi.'));
            exit;

        } catch (PDOException $e) {
            $message = "Hata: " . $e->getMessage();
            $message_type = 'error';
            header("Location: offers.php?status=error&message=" . urlencode($message));
            exit;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Hati App - Teklifler</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>Teklifler</h2>
    <a href="create_offer.php">Yeni Teklif Oluştur</a>
</div>
<div class="card-grid-menu">
    <div class="dashboard-card-icon" style="color: #6c757d;">
        <div class="card-icon-svg" style="background-color: #e9ecef;">
            <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" fill="currentColor" viewBox="0 0 256 256"><path d="M224,128a8,8,0,0,1-8,8H40a8,8,0,0,1,0-16H216A8,8,0,0,1,224,128ZM128,40a8,8,0,0,0-8,8V72a8,8,0,0,0,16,0V48A8,8,0,0,0,128,40ZM128,184a8,8,0,0,0-8,8v24a8,8,0,0,0,16,0V192A8,8,0,0,0,128,184Z"></path></svg>
        </div>
        <span>Toplam Teklif</span>
        <p class="stat-number"><?php echo $stats['total_offers']; ?></p>
    </div>
    <div class="dashboard-card-icon" style="color: #ffc107;">
        <div class="card-icon-svg" style="background-color: #fff8e1;">
            <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" fill="currentColor" viewBox="0 0 256 256"><path d="M232,128a104,104,0,1,1-104-104A104.11,104.11,0,0,1,232,128Zm-8,0a96,96,0,1,0-96,96A96.11,96.11,0,0,0,224,128Zm-96,40a8,8,0,0,1-16,0V128a8,8,0,0,1,16,0Zm0-56a12,12,0,1,1-12-12A12,12,0,0,1,128,112Z"></path></svg>
        </div>
        <span>Taslaklar</span>
        <p class="stat-number"><?php echo $stats['draft_offers']; ?></p>
    </div>
    <div class="dashboard-card-icon" style="color: #28a745;">
        <div class="card-icon-svg" style="background-color: #e6ffed;">
            <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" fill="currentColor" viewBox="0 0 256 256"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm41.66-136.34-56,56a8,8,0,0,1-11.32,0l-24-24a8,8,0,0,1,11.32-11.32L112,148.68l50.34-50.34a8,8,0,0,1,11.32,11.32Z"></path></svg>
        </div>
        <span>Onaylananlar</span>
        <p class="stat-number"><?php echo $stats['accepted_offers']; ?></p>
    </div>
    <div class="dashboard-card-icon" style="color: #dc3545;">
        <div class="card-icon-svg" style="background-color: #ffe6e6;">
            <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" fill="currentColor" viewBox="0 0 256 256"><path d="M224,128a8,8,0,0,1-8,8H40a8,8,0,0,1,0-16H216A8,8,0,0,1,224,128Z"></path></svg>
        </div>
        <span>Reddedilenler</span>
        <p class="stat-number"><?php echo $stats['rejected_offers']; ?></p>
    </div>
</div>
<?php if ($message): ?>
    <p class="message" style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
        <?php echo htmlspecialchars($message); ?>
    </p>
<?php endif; ?>
<h3>Mevcut Teklifler</h3>
<?php if (empty($offers)): ?>
    <p>Henüz kayıtlı bir teklif bulunmamaktadır.</p>
<?php else: ?>
    <div class="list-card-container">
        <?php foreach ($offers as $offer): ?>
            <div class="list-card">
                <div class="list-card-content">
                    <div class="list-card-title"><?php echo htmlspecialchars($offer['customer_name']); ?></div>
                    <div class="list-card-meta">
                        <span><strong>Teklif No:</strong> <?php echo htmlspecialchars($offer['offer_no']); ?></span> |
                        <span><strong>Kategori:</strong> <?php echo htmlspecialchars($offer['category'] ?? '-'); ?></span> |
                        <span><strong>Tarih:</strong> <?php echo htmlspecialchars($offer['offer_date']); ?></span>
                    </div>
                </div>
                <div class="list-card-actions">
                    <form action="offers.php" method="POST" class="inline-form">
                        <input type="hidden" name="action" value="update_status">
                        <input type="hidden" name="offer_id" value="<?php echo $offer['id']; ?>">
                        <select name="new_status" onchange="this.form.submit()">
                            <option value="draft" <?php echo $offer['status'] === 'draft' ? 'selected' : ''; ?>>Taslak</option>
                            <option value="sent" <?php echo $offer['status'] === 'sent' ? 'selected' : ''; ?>>Gönderildi</option>
                            <option value="accepted" <?php echo $offer['status'] === 'accepted' ? 'selected' : ''; ?>>Onaylandı</option>
                            <option value="rejected" <?php echo $offer['status'] === 'rejected' ? 'selected' : ''; ?>>Reddedildi</option>
                        </select>
                    </form>
                    <a href="view_offer.php?id=<?php echo $offer['id']; ?>" class="view-btn">Gör</a>
                    <a href="edit_offer.php?id=<?php echo $offer['id']; ?>" class="view-btn">Düzenle</a>
                    <a href="delete.php?table=offers&id=<?php echo $offer['id']; ?>&redirect=offers.php" class="delete-btn" onclick="return confirm('Bu kaydı silmek istediğinizden emin misiniz?');">Sil</a>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>
</main>
</body>
</html>