<?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();
$discoveries = [];
$message = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';

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

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

try {
    $stmt_list = $conn->prepare("SELECT td.*, p.project_name FROM technical_office_discoveries td LEFT JOIN projects p ON td.project_id = p.id ORDER BY td.discovery_date DESC");
    $stmt_list->execute();
    $discoveries = $stmt_list->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 - Keşifler</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>Keşifler</h2>
</div>
<?php if ($message): ?>
    <p style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;"><?php echo htmlspecialchars($message); ?></p>
<?php endif; ?>
<h3>Mevcut Keşifler</h3>
<?php if (empty($discoveries)): ?>
    <p>Henüz kayıtlı bir keşif bulunmamaktadır.</p>
<?php else: ?>
    <table>
        <thead>
            <tr>
                <th>Keşif No</th>
                <th>Müşteri Adı</th>
                <th>Firma Adı</th>
                <th>Plan Tarihi</th>
                <th>Durum</th>
                <th>İşlemler</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($discoveries as $discovery): ?>
                <tr>
                    <td><a href="view_discovery.php?id=<?php echo $discovery['id']; ?>"><?php echo htmlspecialchars($discovery['discovery_no']); ?></a></td>
                    <td><?php echo htmlspecialchars($discovery['customer_name']); ?></td>
                    <td><?php echo htmlspecialchars($discovery['company_name'] ?? '-'); ?></td>
                    <td><?php echo htmlspecialchars($discovery['planned_date'] ?? '-'); ?></td>
                    <td>
                        <?php $statusInfo = getStatusInfo($discovery['status']); ?>
                        <span class="status <?php echo $statusInfo['class']; ?>"><?php echo $statusInfo['label']; ?></span>
                    </td>
                    <td>
                        <form action="discoveries.php" method="POST" class="inline-form">
                            <input type="hidden" name="action" value="update_status">
                            <input type="hidden" name="discovery_id" value="<?php echo $discovery['id']; ?>">
                            <select name="new_status" onchange="this.form.submit()">
                                <option value="pending" <?php echo $discovery['status'] === 'pending' ? 'selected' : ''; ?>>Planlama Bekliyor</option>
                                <option value="completed_successful" <?php echo $discovery['status'] === 'completed_successful' ? 'selected' : ''; ?>>Keşif Tamamlandı (Teklif Oluştur)</option>
                                <option value="completed_unsuccessful" <?php echo $discovery['status'] === 'completed_unsuccessful' ? 'selected' : ''; ?>>Keşif Tamamlanamadı</option>
                            </select>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>
</main>
<style>
    .inline-form {
        display: inline-block;
        margin: 0;
    }
</style>
</body>
</html>