<?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();
$request = null;
$request_items = [];
$message = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';
$request_id = $_GET['id'] ?? 0;
// Talep onay veya red işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $request_id_post = $_POST['request_id'] ?? 0;
    $new_status = null;
    $message_text = '';
    if ($action === 'approve') {
        $new_status = 'approved';
        // Talebin detaylarını çek
        $stmt = $conn->prepare("SELECT * FROM requests WHERE id = ?");
        $stmt->execute([$request_id_post]);
        $request_data = $stmt->fetch(PDO::FETCH_ASSOC);
        // Keşif Formu için veri hazırlığı
        $discovery_no = 'KEŞ-' . date('Ymd') . '-' . substr(uniqid(), -4);
        $discovery_date = date('Y-m-d');
        $created_by_user_id = $_SESSION['user_id'];
        $notes = "Talep ID: " . $request_data['id'] . " üzerinden otomatik oluşturulmuştur.";
        $action_to_be_taken = implode("\n", array_map(function($item) { return "- " . $item['item_description']; }, $request_items));
        // Technical Office Discoveries tablosuna kaydet
        $stmt_discovery = $conn->prepare("INSERT INTO technical_office_discoveries (discovery_no, customer_name, company_phone, company_address, contact_person, discovery_date, notes, action_to_be_taken, created_by_user_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt_discovery->execute([$discovery_no, $request_data['customer_name'] . ' ' . $request_data['customer_surname'], $request_data['phone_number'], $request_data['address'], $request_data['customer_name'] . ' ' . $request_data['customer_surname'], $discovery_date, $notes, $action_to_be_taken, $created_by_user_id]);
        $new_discovery_id = $conn->lastInsertId();
        // Talebin durumunu güncelle
        $stmt = $conn->prepare("UPDATE requests SET status = ? WHERE id = ?");
        $stmt->execute([$new_status, $request_id_post]);
        header("Location: view_discovery.php?id=$new_discovery_id");
        exit;
    } elseif ($action === 'rejected') {
        $new_status = 'rejected';
        $message_text = 'Talep başarıyla reddedildi.';
        $stmt = $conn->prepare("UPDATE requests SET status = ? WHERE id = ?");
        $stmt->execute([$new_status, $request_id_post]);
        header("Location: view_request.php?id=$request_id_post&status=success&message=" . urlencode($message_text));
        exit;
    } else {
        $new_status = null;
    }
}
// Talep detaylarını çekme
if ($request_id > 0) {
    try {
        $stmt = $conn->prepare("SELECT r.*, u.name as created_by FROM requests r JOIN users u ON r.created_by_user_id = u.id WHERE r.id = ?");
        $stmt->execute([$request_id]);
        $request = $stmt->fetch(PDO::FETCH_ASSOC);
        $stmt_items = $conn->prepare("SELECT * FROM request_items WHERE request_id = ?");
        $stmt_items->execute([$request_id]);
        $request_items = $stmt_items->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $message = 'Hata: ' . $e->getMessage();
        $message_type = 'error';
    }
}
if (!$request) {
    die("Talep kaydı bulunamadı.");
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Talep Detayı</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>Talep Detayı</h2>
    <?php if ($message): ?>
        <p class="message" style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
            <?php echo htmlspecialchars($message); ?>
        </p>
    <?php endif; ?>
    <div class="detail-box">
        <h3 class="detail-box-title">Müşteri Bilgileri</h3>
        <div class="detail-grid">
            <div><strong>Müşteri Adı:</strong> <?php echo htmlspecialchars($request['customer_name'] . ' ' . $request['customer_surname']); ?></div>
            <div><strong>Telefon:</strong> <?php echo htmlspecialchars($request['phone_number']); ?></div>
            <div><strong>Talep Tarihi:</strong> <?php echo htmlspecialchars($request['request_date']); ?></div>
            <div><strong>Oluşturan:</strong> <?php echo htmlspecialchars($request['created_by']); ?></div>
            <div class="full-width"><strong>Adres:</strong> <?php echo htmlspecialchars($request['address']); ?></div>
            <div class="full-width"><strong>Durum:</strong>
                <?php $statusInfo = getStatusInfo($request['status']); ?>
                <span class="status <?php echo $statusInfo['class']; ?>"><?php echo $statusInfo['label']; ?></span>
            </div>
        </div>
    </div>
    
    <div class="detail-box" style="margin-top: 20px;">
        <h3 class="detail-box-title">Talep Kalemleri</h3>
        <?php if (empty($request_items)): ?>
            <p>Talep edilen iş kalemi bulunmamaktadır.</p>
        <?php else: ?>
            <ul>
                <?php foreach ($request_items as $item): ?>
                    <li><?php echo htmlspecialchars($item['item_description']); ?></li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>
    </div>
    
    <?php if ($request['status'] === 'pending' && $_SESSION['user_role'] === 'admin'): ?>
    <div class="detail-box" style="margin-top: 20px;">
        <h3 class="detail-box-title">İşlem Yap</h3>
        <form action="view_request.php?id=<?php echo $request['id']; ?>" method="POST">
            <input type="hidden" name="request_id" value="<?php echo $request['id']; ?>">
            <div class="form-actions" style="justify-content: flex-start; gap: 10px;">
                <button type="submit" name="action" value="approve" class="btn btn-primary">Talebi Onayla & Keşif Oluştur</button>
                <button type="submit" name="action" value="rejected" class="btn btn-danger">Talebi Reddet</button>
            </div>
        </form>
    </div>
    <?php endif; ?>
</main>
</body>
</html>