<?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();
$discovery = null;
$discovery_id = $_GET['id'] ?? 0;

// Keşif durumunu güncelleme işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $discovery_id_post = $_POST['discovery_id'] ?? 0;
    
    if ($action === 'plan') {
        $planned_date = $_POST['planned_date'] ?? null;
        $planned_time = $_POST['planned_time'] ?? null;
        try {
            $stmt = $conn->prepare("UPDATE technical_office_discoveries SET status = 'pending_plan', planned_date = ?, planned_time = ? WHERE id = ?");
            $stmt->execute([$planned_date, $planned_time, $discovery_id_post]);
            header("Location: view_discovery.php?id=$discovery_id_post&status=success&message=" . urlencode('Keşif planı başarıyla oluşturuldu.'));
            exit;
        } catch (PDOException $e) {
            die("Hata: " . $e->getMessage());
        }
    } elseif ($action === 'complete_successful') {
        $new_status = 'completed_successful';
        $message_text = 'Keşif başarıyla tamamlandı. Teklif oluşturma sayfasına yönlendiriliyorsunuz...';
        try {
            $stmt = $conn->prepare("UPDATE technical_office_discoveries SET status = ? WHERE id = ?");
            $stmt->execute([$new_status, $discovery_id_post]);
            header("Location: create_offer.php?discovery_id=$discovery_id_post");
            exit;
        } catch (PDOException $e) {
            die("Hata: " . $e->getMessage());
        }
    } elseif ($action === 'complete_unsuccessful') {
        $new_status = 'completed_unsuccessful';
        $message_text = 'Keşif tamamlanamadı olarak işaretlendi.';
        try {
            $stmt = $conn->prepare("UPDATE technical_office_discoveries SET status = ? WHERE id = ?");
            $stmt->execute([$new_status, $discovery_id_post]);
            header("Location: view_discovery.php?id=$discovery_id_post&status=success&message=" . urlencode($message_text));
            exit;
        } catch (PDOException $e) {
            die("Hata: " . $e->getMessage());
        }
    }
}

if ($discovery_id > 0) {
    try {
        $stmt = $conn->prepare("SELECT td.*, p.project_name FROM technical_office_discoveries td LEFT JOIN projects p ON td.project_id = p.id WHERE td.id = ?");
        $stmt->execute([$discovery_id]);
        $discovery = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        die("Hata: " . $e->getMessage());
    }
}
if (!$discovery) {
    die("Keşif kaydı bulunamadı.");
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Keşif Detayı: <?php echo htmlspecialchars($discovery['discovery_no']); ?></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'; ?>
    <h2>Keşif Detayı</h2>
    <div class="detail-box">
        <h3 class="detail-box-title">Keşif Bilgileri</h3>
        <div class="detail-grid">
            <div><strong>Keşif No:</strong> <?php echo htmlspecialchars($discovery['discovery_no']); ?></div>
            <div><strong>Müşteri Adı:</strong> <?php echo htmlspecialchars($discovery['customer_name']); ?></div>
            <div><strong>Firma Adı:</strong> <?php echo htmlspecialchars($discovery['company_name'] ?? '-'); ?></div>
            <div><strong>Firma Numarası:</strong> <?php echo htmlspecialchars($discovery['company_phone'] ?? '-'); ?></div>
            <div><strong>Görüşülen Kişi:</strong> <?php echo htmlspecialchars($discovery['contact_person'] ?? '-'); ?></div>
            <div><strong>Keşif Tarihi:</strong> <?php echo htmlspecialchars($discovery['discovery_date']); ?></div>
            <div><strong>İlgili Proje:</strong> <?php echo htmlspecialchars($discovery['project_name'] ?? '-'); ?></div>
            <div class="full-width"><strong>Durum:</strong> 
                <?php $statusInfo = getStatusInfo($discovery['status']); ?>
                <span class="status <?php echo $statusInfo['class']; ?>"><?php echo $statusInfo['label']; ?></span>
            </div>
        </div>
    </div>
    <div class="detail-box">
        <h3 class="detail-box-title">Adres ve Yapılacak İşlem</h3>
        <div class="detail-grid">
            <div class="full-width"><strong>Firma Adresi:</strong> <?php echo htmlspecialchars($discovery['company_address'] ?? '-'); ?></div>
            <div class="full-width"><strong>Yapılacak İşlem:</strong> <?php echo nl2br(htmlspecialchars($discovery['action_to_be_taken'] ?? '-')); ?></div>
        </div>
    </div>
    <div class="detail-box">
        <h3 class="detail-box-title">Notlar</h3>
        <div class="full-width"><pre><?php echo nl2br(htmlspecialchars($discovery['notes'] ?? '-')); ?></pre></div>
    </div>
    
    <?php if ($discovery['status'] === 'pending' || $discovery['status'] === 'pending_plan'): ?>
        <hr>
        <div class="detail-box">
            <h3>Keşif Planlama</h3>
            <p><strong>Planlanan Tarih:</strong> <?php echo htmlspecialchars($discovery['planned_date'] ?? 'Belirlenmedi'); ?>
            <p><strong>Planlanan Saat:</strong> <?php echo htmlspecialchars($discovery['planned_time'] ?? 'Belirlenmedi'); ?>
            <form action="view_discovery.php?id=<?php echo $discovery['id']; ?>" method="POST">
                <input type="hidden" name="discovery_id" value="<?php echo $discovery['id']; ?>">
                <div class="form-grid">
                    <div class="form-group">
                        <label for="planned_date">Tarih Belirleyin</label>
                        <input type="date" id="planned_date" name="planned_date" required>
                    </div>
                    <div class="form-group">
                        <label for="planned_time">Saat Seçiniz</label>
                        <input type="time" id="planned_time" name="planned_time" required>
                    </div>
                </div>
                <button type="submit" name="action" value="plan">Keşif Planlaması Yap</button>
            </form>
        </div>
    <?php endif; ?>

    <?php if ($discovery['status'] === 'completed_successful' || $discovery['status'] === 'completed_unsuccessful'): ?>
        <hr>
        <div class="detail-box">
            <h3>İşlem Sonucu</h3>
            <p>Bu keşif tamamlanmıştır.</p>
        </div>
    <?php elseif ($discovery['status'] === 'pending_plan'): ?>
        <hr>
        <div class="detail-box">
            <h3>Keşif Tamamlama</h3>
            <p>Keşif tamamlandığında aşağıdan durumu güncelleyebilirsiniz.</p>
            <form action="view_discovery.php?id=<?php echo $discovery['id']; ?>" method="POST">
                <input type="hidden" name="discovery_id" value="<?php echo $discovery['id']; ?>">
                <button type="submit" name="action" value="complete_successful" style="background-color: green; color: white;">Keşif Tamamlandı & Teklif Oluştur</button>
                <button type="submit" name="action" value="complete_unsuccessful" style="background-color: red; color: white;">Keşif Tamamlanamadı</button>
            </form>
        </div>
    <?php endif; ?>
</main>
</body>
</html>