<?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;
$message = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';
$request_id = $_GET['id'] ?? 0;
$projects = [];
$suppliers = [];
$subcontractors = [];

// Talep durumunu güncelleme işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_status') {
    $request_id_post = $_POST['request_id'] ?? 0;
    $new_status = $_POST['new_status'] ?? null;
    $project_id = $_POST['project_id'] ?? null;
    $supplier_id = $_POST['supplier_id'] ?? null;

    if ($request_id_post > 0 && $new_status) {
        try {
            $stmt = $conn->prepare("UPDATE purchase_requests SET status = ?, project_id = ?, supplier_id = ? WHERE id = ?");
            $stmt->execute([$new_status, $project_id, $supplier_id, $request_id_post]);
            
            header("Location: view_purchase_request.php?id=$request_id_post&status=success&message=" . urlencode('Talep durumu güncellendi.'));
            exit;
        } catch (PDOException $e) {
            $message = 'Hata: İşlem sırasında bir sorun oluştu. ' . $e->getMessage();
            $message_type = 'error';
            header("Location: view_purchase_request.php?id=$request_id_post&status=error&message=" . urlencode($message));
            exit;
        }
    }
}

// Talep detaylarını çekme
if ($request_id > 0) {
    try {
        $stmt = $conn->prepare("SELECT pr.*, u.name as user_name, si.item_name, si.unit, p.project_name, s.supplier_name, sc.subcontractor_name FROM purchase_requests pr JOIN users u ON pr.requested_by_user_id = u.id LEFT JOIN stock_items si ON pr.item_id = si.id LEFT JOIN projects p ON pr.project_id = p.id LEFT JOIN suppliers s ON pr.supplier_id = s.id LEFT JOIN subcontractors sc ON pr.subcontractor_id = sc.id WHERE pr.id = ?");
        $stmt->execute([$request_id]);
        $request = $stmt->fetch(PDO::FETCH_ASSOC);

        $stmt_projects = $conn->prepare("SELECT id, project_name FROM projects");
        $stmt_projects->execute();
        $projects = $stmt_projects->fetchAll(PDO::FETCH_ASSOC);

        $stmt_suppliers = $conn->prepare("SELECT id, supplier_name FROM suppliers");
        $stmt_suppliers->execute();
        $suppliers = $stmt_suppliers->fetchAll(PDO::FETCH_ASSOC);

        $stmt_subcontractors = $conn->prepare("SELECT id, subcontractor_name FROM subcontractors");
        $stmt_subcontractors->execute();
        $subcontractors = $stmt_subcontractors->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>Ürün Talebi 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>Ürün Talebi Detayı</h2>
    <div class="detail-grid">
        <div><strong>Talep No:</strong> <?php echo htmlspecialchars($request['request_no']); ?></div>
        <div><strong>Talep Eden:</strong> <?php echo htmlspecialchars($request['user_name']); ?></div>
        <div><strong>Bölüm:</strong> <?php echo htmlspecialchars($request['department']); ?></div>
        <div><strong>Talep Tarihi:</strong> <?php echo htmlspecialchars($request['request_date']); ?></div>
        <div><strong>Ürün Adı:</strong> <?php echo htmlspecialchars($request['item_name'] ?? '-'); ?></div>
        <div><strong>Tedarikçi:</strong> <?php echo htmlspecialchars($request['supplier_name'] ?? '-'); ?></div>
        <div><strong>Taşeron:</strong> <?php echo htmlspecialchars($request['subcontractor_name'] ?? '-'); ?></div>
        <div><strong>Birim:</strong> <?php echo htmlspecialchars($request['unit'] ?? '-'); ?></div>
        <div><strong>Miktar:</strong> <?php echo htmlspecialchars($request['quantity']); ?></div>
        <div><strong>Aciliyet:</strong> <?php echo htmlspecialchars(ucfirst($request['urgency'])); ?></div>
    </div>
    <hr>
    <div class="detail-box">
        <h3 class="detail-box-title">Talep Durumu</h3>
        <p><strong>Durum:</strong>
            <?php $statusInfo = getStatusInfo($request['status']); ?>
            <span class="status <?php echo $statusInfo['class']; ?>"><?php echo $statusInfo['label']; ?></span>
        </p>
        <?php if ($_SESSION['user_role'] === 'admin'): ?>
            <form action="view_purchase_request.php?id=<?php echo $request['id']; ?>" method="POST" class="inline-form">
                <input type="hidden" name="action" value="update_status">
                <input type="hidden" name="request_id" value="<?php echo $request['id']; ?>">
                <div class="form-grid">
                    <div class="form-group">
                        <label for="new_status">Durum Güncelle:</label>
                        <select name="new_status">
                            <option value="waiting_approval" <?php echo $request['status'] === 'waiting_approval' ? 'selected' : ''; ?>>Onay Bekliyor</option>
                            <option value="approved" <?php echo $request['status'] === 'approved' ? 'selected' : ''; ?>>Onaylandı</option>
                            <option value="rejected" <?php echo $request['status'] === 'rejected' ? 'selected' : ''; ?>>Reddedildi</option>
                            <option value="ordered" <?php echo $request['status'] === 'ordered' ? 'selected' : ''; ?>>Sipariş Edildi</option>
                            <option value="completed" <?php echo $request['status'] === 'completed' ? 'selected' : ''; ?>>Tamamlandı</option>
                        </select>
                    </div>
                    <?php if (in_array($request['status'], ['approved', 'ordered', 'completed'])): ?>
                        <div class="form-group">
                            <label for="project_id">Proje:</label>
                            <select name="project_id">
                                <option value="">Seçiniz</option>
                                <?php foreach ($projects as $project): ?>
                                    <option value="<?php echo $project['id']; ?>" <?php echo ($request['project_id'] == $project['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($project['project_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="supplier_id">Tedarikçi:</label>
                            <select name="supplier_id">
                                <option value="">Seçiniz</option>
                                <?php foreach ($suppliers as $supplier): ?>
                                    <option value="<?php echo $supplier['id']; ?>" <?php echo ($request['supplier_id'] == $supplier['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($supplier['supplier_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endif; ?>
                </div>
                <button type="submit" style="margin-top: 10px;">Durumu Güncelle</button>
            </form>
        <?php endif; ?>
    </div>
    <div class="detail-box">
        <h3 class="detail-box-title">Ek Notlar</h3>
        <pre><?php echo htmlspecialchars($request['notes'] ?? '-'); ?></pre>
    </div>
</main>
</body>
</html>