<?php
session_start();

// Debug
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "Debug create_request.php<br>";
echo "Method: " . $_SERVER['REQUEST_METHOD'] . "<br>";
echo "Session data: ";
var_dump($_SESSION);
echo "<br>POST data: ";
var_dump($_POST);

require_once 'db.php';

if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    echo "User not logged in, redirecting...<br>";
    header('Location: member.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo "Processing POST request...<br>";
    
    $userId = $_SESSION['user_id'];
    $subject = trim($_POST['subject']);
    $message = trim($_POST['message']);
    $priority = $_POST['priority'];
    $projectId = !empty($_POST['project_id']) ? (int)$_POST['project_id'] : null;
    
    echo "Parsed data:<br>";
    echo "User ID: $userId<br>";
    echo "Subject: $subject<br>";
    echo "Message: $message<br>";
    echo "Priority: $priority<br>";
    echo "Project ID: $projectId<br>";
    
    try {
        if (empty($subject) || empty($message)) {
            throw new Exception('Subject and message are required');
        }
        
        if (!in_array($priority, ['low', 'medium', 'high', 'urgent'])) {
            throw new Exception('Invalid priority level');
        }
        
        if ($projectId) {
            $projectCheck = $pdo->prepare("SELECT id FROM projects WHERE id = ? AND user_id = ?");
            $projectCheck->execute([$projectId, $userId]);
            if (!$projectCheck->fetch()) {
                throw new Exception('Invalid project selected');
            }
        }
        
        echo "About to insert into database...<br>";
        
        $stmt = $pdo->prepare("INSERT INTO requests (user_id, project_id, subject, message, priority, status) VALUES (?, ?, ?, ?, ?, 'open')");
        $result = $stmt->execute([$userId, $projectId, $subject, $message, $priority]);
        
        echo "Insert result: " . ($result ? 'SUCCESS' : 'FAILED') . "<br>";
        echo "Last insert ID: " . $pdo->lastInsertId() . "<br>";
        
        if ($result) {
            echo "Redirecting to dashboard with success...<br>";
            header('Location: dashboard.php?success=request_created');
            exit();
        } else {
            throw new Exception('Failed to insert request');
        }
        
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage() . "<br>";
        header('Location: dashboard.php?error=' . urlencode($e->getMessage()));
        exit();
    }
    
} else {
    echo "Not POST request, redirecting...<br>";
    header('Location: dashboard.php');
    exit();
}
?>