<?php
session_start();
require_once 'db.php';

if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    header('HTTP/1.1 401 Unauthorized');
    exit();
}

$userId = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action'])) {
    $action = $_GET['action'];
    
    try {
        switch ($action) {
            case 'get_request_details':
                $requestId = (int)$_GET['id'];
                
                if (empty($requestId)) {
                    throw new Exception('Request ID is required');
                }
                
                $requestStmt = $pdo->prepare("
                    SELECT r.*, p.project_name 
                    FROM requests r 
                    LEFT JOIN projects p ON r.project_id = p.id 
                    WHERE r.id = ? AND r.user_id = ?
                ");
                $requestStmt->execute([$requestId, $userId]);
                $request = $requestStmt->fetch();
                
                if (!$request) {
                    throw new Exception('Request not found');
                }
                
                $responsesStmt = $pdo->prepare("SELECT * FROM responses WHERE request_id = ? ORDER BY created_at ASC");
                $responsesStmt->execute([$requestId]);
                $responses = $responsesStmt->fetchAll();
                
                function getStatusColor($status) {
                    switch ($status) {
                        case 'open': return 'bg-orange-100 text-orange-800';
                        case 'in_progress': return 'bg-blue-100 text-blue-800';
                        case 'resolved': return 'bg-green-100 text-green-800';
                        case 'closed': return 'bg-gray-100 text-gray-800';
                        default: return 'bg-gray-100 text-gray-800';
                    }
                }
                
                function getPriorityColor($priority) {
                    switch ($priority) {
                        case 'low': return 'bg-gray-100 text-gray-800';
                        case 'medium': return 'bg-blue-100 text-blue-800';
                        case 'high': return 'bg-orange-100 text-orange-800';
                        case 'urgent': return 'bg-red-100 text-red-800';
                        default: return 'bg-gray-100 text-gray-800';
                    }
                }
                
                ob_start();
                ?>

            <div class="space-y-6">
                <div class="border-b border-gray-200 pb-4">
                    <div class="flex items-start justify-between mb-3">
                        <h4 class="text-lg font-medium text-gray-900"><?= htmlspecialchars($request['subject']) ?></h4>
                        <div class="flex space-x-2">
                            <span class="px-2 py-1 text-xs rounded-full <?= getStatusColor($request['status']) ?>">
                                <?= ucfirst(str_replace('_', ' ', $request['status'])) ?>
                            </span>
                            <span class="px-2 py-1 text-xs rounded-full <?= getPriorityColor($request['priority']) ?>">
                                <?= ucfirst($request['priority']) ?>
                            </span>
                        </div>
                    </div>
                    
                    <?php if ($request['project_name']): ?>
                        <p class="text-sm text-gray-600 mb-2"><strong>Project:</strong> <?= htmlspecialchars($request['project_name']) ?></p>
                    <?php endif; ?>
                    
                    <p class="text-sm text-gray-600 mb-3"><strong>Created:</strong> <?= date('F j, Y \a\t g:i A', strtotime($request['created_at'])) ?></p>
                    
                    <div class="bg-gray-50 rounded-lg p-4">
                        <p class="text-gray-800"><?= nl2br(htmlspecialchars($request['message'])) ?></p>
                    </div>
                </div>
                
                <?php if (!empty($responses)): ?>
                    <div>
                        <h5 class="text-md font-medium text-gray-900 mb-4">Responses</h5>
                        <div class="space-y-4">
                            <?php foreach ($responses as $response): ?>
                                <div class="<?= $response['is_admin_response'] ? 'bg-blue-50 border-l-4 border-blue-400' : 'bg-gray-50 border-l-4 border-gray-400' ?> p-4 rounded-r-lg">
                                    <div class="flex items-center justify-between mb-2">
                                        <p class="text-sm font-medium text-gray-900"><?= htmlspecialchars($response['responder_name']) ?></p>
                                        <p class="text-xs text-gray-500"><?= date('M j, Y \a\t g:i A', strtotime($response['created_at'])) ?></p>
                                    </div>
                                    <p class="text-gray-800"><?= nl2br(htmlspecialchars($response['message'])) ?></p>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="text-center py-8 text-gray-500">
                        <p>No responses yet. We'll get back to you soon!</p>
                    </div>
                <?php endif; ?>
            </div>
            <?php
            $html = ob_get_clean();
            
            header('Content-Type: application/json');
            echo json_encode([
                'success' => true,
                'html' => $html
            ]);
            exit();
            
        case 'get_project_logs':
            $projectId = (int)$_GET['id'];
            
            if (empty($projectId)) {
                throw new Exception('Project ID is required');
            }
            
            $projectCheck = $pdo->prepare("SELECT id FROM projects WHERE id = ? AND user_id = ?");
            $projectCheck->execute([$projectId, $userId]);
            if (!$projectCheck->fetch()) {
                throw new Exception('Project not found');
            }
            
            $logsStmt = $pdo->prepare("SELECT * FROM project_logs WHERE project_id = ? ORDER BY created_at DESC");
            $logsStmt->execute([$projectId]);
            $logs = $logsStmt->fetchAll();
            
            function getLogTypeIcon($type) {
                switch ($type) {
                    case 'status_change': return '<svg class="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>';
                    case 'milestone': return '<svg class="w-4 h-4 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z"></path></svg>';
                    case 'update': return '<svg class="w-4 h-4 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>';
                    case 'note': return '<svg class="w-4 h-4 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>';
                    default: return '<svg class="w-4 h-4 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>';
                }
            }
            
            ob_start();
            ?>
            <?php if (!empty($logs)): ?>
                <div class="space-y-4">
                    <?php foreach ($logs as $log): ?>
                        <div class="border border-gray-200 rounded-lg p-4 hover:bg-gray-50 transition duration-200">
                            <div class="flex items-start space-x-3">
                                <div class="flex-shrink-0 mt-1">
                                    <?= getLogTypeIcon($log['log_type']) ?>
                                </div>
                                <div class="flex-1">
                                    <div class="flex items-center justify-between mb-1">
                                        <h6 class="text-sm font-medium text-gray-900"><?= htmlspecialchars($log['title']) ?></h6>
                                        <span class="text-xs text-gray-500"><?= date('M j, Y', strtotime($log['created_at'])) ?></span>
                                    </div>
                                    
                                    <?php if ($log['description']): ?>
                                        <p class="text-sm text-gray-600 mb-2"><?= htmlspecialchars($log['description']) ?></p>
                                    <?php endif; ?>
                                    
                                    <?php if ($log['old_status'] && $log['new_status']): ?>
                                        <div class="text-xs text-gray-500">
                                            Status: <span class="font-medium"><?= ucfirst(str_replace('_', ' ', $log['old_status'])) ?></span> → 
                                            <span class="font-medium"><?= ucfirst(str_replace('_', ' ', $log['new_status'])) ?></span>
                                        </div>
                                    <?php elseif ($log['new_status']): ?>
                                        <div class="text-xs text-gray-500">
                                            Status: <span class="font-medium"><?= ucfirst(str_replace('_', ' ', $log['new_status'])) ?></span>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <div class="text-xs text-gray-400 mt-2">
                                        by <?= htmlspecialchars($log['created_by']) ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="text-center py-12 text-gray-500">
                    <svg class="w-16 h-16 mx-auto mb-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                    <p class="text-lg">No logs yet</p>
                    <p class="text-sm">Project logs will appear here as work progresses</p>
                </div>
            <?php endif; ?>
            <?php
            $html = ob_get_clean();
            
            header('Content-Type: application/json');
            echo json_encode([
                'success' => true,
                'html' => $html
            ]);
            exit();
            
        default:
            throw new Exception('Invalid action');
    }
    
} catch (Exception $e) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
    exit();
}

} else {
header(‘HTTP/1.1 405 Method Not Allowed’);
exit();
}
?>