<?php
/**
 * Report Submission Page
 * GHAMECC Choir Management Platform
 */

// Include authentication functions
require_once '../includes/auth.php';

// Include database functions
require_once '../config/database.php';

// Require login
requireLogin();

// Process form submissions
$success = '';
$error = '';

// Get user information and role
$userId = $_SESSION['user_id'];
$userInfo = fetchRow("SELECT u.*, r.role_key, r.name as role_name 
                     FROM users u 
                     JOIN roles r ON u.role_id = r.id 
                     WHERE u.id = ?", [$userId]);

// Log user info for debugging
logInfo("User attempting to access reports/submit.php", [
    'user_id' => $userId,
    'role' => $userInfo['role_key'] ?? 'unknown',
    'session_society_id' => $_SESSION['society_id'] ?? 'not set',
    'session_circuit_id' => $_SESSION['circuit_id'] ?? 'not set',
    'session_diocese_id' => $_SESSION['diocese_id'] ?? 'not set'
]);

// Determine report submission direction based on user role
$targetLevels = [];
$userLevel = '';
$userEntityId = 0;

// Fetch report types from database
$reportTypes = [];
$reportTypesQuery = "SELECT id, name, category FROM report_types ORDER BY category, name";
$reportTypesResult = $conn->query($reportTypesQuery);

if ($reportTypesResult) {
    while ($row = $reportTypesResult->fetch_assoc()) {
        // Create a URL-friendly key from the name
        $key = strtolower(str_replace([' ', '-'], '_', $row['name']));
        $reportTypes[$key] = [
            'id' => $row['id'],
            'name' => $row['name'],
            'category' => $row['category'] ?? 'General'
        ];
    }
    
    // Log retrieved report types
    logDebug("Retrieved report types from database", [
        'count' => count($reportTypes),
        'types' => array_keys($reportTypes)
    ]);
} else {
    logError("Failed to fetch report types", [
        'error' => $conn->error,
        'query' => $reportTypesQuery
    ]);
}

// Get user's associated entity (society, circuit, diocese)
if (in_array($userInfo['role_key'], ['choirmaster', 'society_secretary', 'society_treasurer'])) {
    $userLevel = 'society';
    
    // First check if user has society_id directly in the session
    if (isset($_SESSION['society_id']) && !empty($_SESSION['society_id'])) {
        $societyId = $_SESSION['society_id'];
        $userEntity = fetchRow("SELECT s.*, c.name as circuit_name, c.id as circuit_id, d.name as diocese_name, d.id as diocese_id 
                              FROM societies s
                              JOIN circuits c ON s.circuit_id = c.id 
                              JOIN dioceses d ON c.diocese_id = d.id 
                              WHERE s.id = ?", [$societyId]);
        
        logInfo("Retrieved society from session", [
            'society_id' => $societyId,
            'found_entity' => !empty($userEntity) ? 'yes' : 'no'
        ]);
    } else {
        // Check if society_id is in the user record
        $userSocietyId = $userInfo['society_id'] ?? null;
        
        if ($userSocietyId) {
            // Store in session for future use
            $_SESSION['society_id'] = $userSocietyId;
            
            $userEntity = fetchRow("SELECT s.*, c.name as circuit_name, c.id as circuit_id, d.name as diocese_name, d.id as diocese_id 
                                  FROM societies s
                                  JOIN circuits c ON s.circuit_id = c.id 
                                  JOIN dioceses d ON c.diocese_id = d.id 
                                  WHERE s.id = ?", [$userSocietyId]);
            
            logInfo("Retrieved society from user record", [
                'society_id' => $userSocietyId,
                'found_entity' => !empty($userEntity) ? 'yes' : 'no'
            ]);
        } else {
            // Fallback to checking via member association
            $memberQuery = "SELECT m.* FROM users u JOIN members m ON u.member_id = m.id WHERE u.id = ?";
            $memberInfo = fetchRow($memberQuery, [$userId]);
            
            logInfo("Retrieved member info for society lookup", [
                'user_id' => $userId,
                'member_id' => $memberInfo['id'] ?? 'not found',
                'society_id' => $memberInfo['society_id'] ?? 'not set'
            ]);
            
            if ($memberInfo && isset($memberInfo['society_id'])) {
                // Store society_id in session for future use
                $_SESSION['society_id'] = $memberInfo['society_id'];
                
                // Update user record with society_id
                executeQuery("UPDATE users SET society_id = ? WHERE id = ?", [$memberInfo['society_id'], $userId]);
                
                $userEntity = fetchRow("SELECT s.*, c.name as circuit_name, c.id as circuit_id, d.name as diocese_name, d.id as diocese_id 
                                      FROM societies s
                                      JOIN circuits c ON s.circuit_id = c.id 
                                      JOIN dioceses d ON c.diocese_id = d.id 
                                      WHERE s.id = ?", [$memberInfo['society_id']]);
                
                logInfo("Retrieved society from member association", [
                    'society_id' => $memberInfo['society_id'],
                    'found_entity' => !empty($userEntity) ? 'yes' : 'no'
                ]);
            } else {
                logError("Failed to find society for user", [
                    'user_id' => $userId,
                    'role' => $userInfo['role_key'] ?? 'unknown'
                ]);
            }
        }
    }
    
    if ($userEntity) {
        $userEntityId = $userEntity['id'];
        // Society users can only submit to their circuit
        $targetLevels = [
            'circuit' => [
                'id' => $userEntity['circuit_id'],
                'name' => $userEntity['circuit_name']
            ]
        ];
    }
} elseif (in_array($userInfo['role_key'], ['circuit_chairman', 'circuit_secretary', 'circuit_dom', 'circuit_treasurer'])) {
    $userLevel = 'circuit';
    
    // First check if user has circuit_id directly in the session
    if (isset($_SESSION['circuit_id']) && !empty($_SESSION['circuit_id'])) {
        $circuitId = $_SESSION['circuit_id'];
        $userEntity = fetchRow("SELECT c.*, d.name as diocese_name, d.id as diocese_id 
                              FROM circuits c
                              JOIN dioceses d ON c.diocese_id = d.id 
                              WHERE c.id = ?", [$circuitId]);
        
        logInfo("Retrieved circuit from session", [
            'circuit_id' => $circuitId,
            'found_entity' => $userEntity ? 'yes' : 'no'
        ]);
    } else {
        // Try to get circuit from user record directly
        $userCircuitId = $userInfo['circuit_id'] ?? null;
        
        if ($userCircuitId) {
            $userEntity = fetchRow("SELECT c.*, d.name as diocese_name, d.id as diocese_id 
                                  FROM circuits c
                                  JOIN dioceses d ON c.diocese_id = d.id 
                                  WHERE c.id = ?", [$userCircuitId]);
        } else {
            // Try to get circuit from member association via society
            $userEntity = fetchRow("SELECT c.*, d.name as diocese_name, d.id as diocese_id 
                                  FROM users u 
                                  JOIN members m ON u.member_id = m.id
                                  JOIN societies s ON m.society_id = s.id
                                  JOIN circuits c ON s.circuit_id = c.id
                                  JOIN dioceses d ON c.diocese_id = d.id
                                  WHERE u.id = ?", [$userId]);
        }
    }
    
    if ($userEntity) {
        $userEntityId = $userEntity['id'];
        // Circuit users can submit to their diocese
        $targetLevels = [
            'diocese' => [
                'id' => $userEntity['diocese_id'],
                'name' => $userEntity['diocese_name']
            ]
        ];
        
        logDebug("Circuit user target levels", [
            'user_id' => $userId,
            'circuit_id' => $userEntityId,
            'diocese_id' => $userEntity['diocese_id'],
            'diocese_name' => $userEntity['diocese_name']
        ]);
    }
} elseif (in_array($userInfo['role_key'], ['diocesan_chairman', 'diocesan_secretary', 'diocesan_dom', 'diocesan_treasurer'])) {
    $userLevel = 'diocese';
    $userEntity = fetchRow("SELECT d.* 
                           FROM members m 
                           JOIN dioceses d ON m.diocese_id = d.id 
                           WHERE m.id = (SELECT member_id FROM users WHERE id = $userId)");
    
    if ($userEntity) {
        $userEntityId = $userEntity['id'];
        $targetLevels = [
            'connexional' => [
                'id' => 1, // Assuming there's only one connexional level
                'name' => 'Connexional Office'
            ]
        ];
    }
} elseif (in_array($userInfo['role_key'], ['admin'])) {
    // Admin can submit reports to any level
    $userLevel = 'admin';
    
    // Get all dioceses
    $dioceses = fetchRows("SELECT id, name FROM dioceses ORDER BY name");
    foreach ($dioceses as $diocese) {
        $targetLevels['diocese_' . $diocese['id']] = [
            'id' => $diocese['id'],
            'name' => $diocese['name'] . ' (Diocese)'
        ];
    }
    
    // Get all circuits
    $circuits = fetchRows("SELECT c.id, c.name, d.name as diocese_name 
                          FROM circuits c 
                          JOIN dioceses d ON c.diocese_id = d.id 
                          ORDER BY d.name, c.name");
    foreach ($circuits as $circuit) {
        $targetLevels['circuit_' . $circuit['id']] = [
            'id' => $circuit['id'],
            'name' => $circuit['name'] . ' (' . $circuit['diocese_name'] . ' Diocese)'
        ];
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get form data
    $reportType = $_POST['report_type'] ?? '';
    $targetLevel = $_POST['target_level'] ?? '';
    $title = $_POST['title'] ?? '';
    $content = $_POST['content'] ?? '';
    $reportStartDate = $_POST['report_start_date'] ?? '';
    $reportEndDate = $_POST['report_end_date'] ?? '';
    
    // Initialize target variables
    $targetId = 0;
    $targetType = '';
    
    // Get the numeric report_type_id from our reportTypes array
    $reportTypeId = isset($reportTypes[$reportType]) ? $reportTypes[$reportType]['id'] : 0;
    
    // Log form submission data
    logDebug("Report submission form data", [
        'report_type' => $reportType,
        'report_type_id' => $reportTypeId,
        'target_level' => $targetLevel,
        'title' => $title,
        'content_length' => strlen($content),
        'report_start_date' => $reportStartDate,
        'report_end_date' => $reportEndDate
    ]);
    
    // Parse target level
    if (strpos($targetLevel, '_') !== false) {
        list($targetType, $targetId) = explode('_', $targetLevel);
        $targetId = (int)$targetId;
    } else {
        $targetType = $targetLevel;
        $targetId = $targetLevels[$targetLevel]['id'] ?? 0;
    }
    
    // Log parsed target information
    logDebug("Parsed target information", [
        'target_type' => $targetType,
        'target_id' => $targetId,
        'user_level' => $userLevel,
        'user_entity_id' => $userEntityId
    ]);
    
    // Validate required fields with detailed logging
    $validationErrors = [];
    if (empty($reportType)) $validationErrors[] = 'report_type';
    if (empty($targetLevel)) $validationErrors[] = 'target_level';
    if (empty($title)) $validationErrors[] = 'title';
    if (empty($content)) $validationErrors[] = 'content';
    
    if (!empty($validationErrors)) {
        $error = "All fields are required.";
        logError("Form validation failed", [
            'missing_fields' => $validationErrors
        ]);
    } else {
        // Handle file upload if present
        $attachmentPath = null;
        if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = '../uploads/reports/';
            
            // Create directory if it doesn't exist
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            
            $fileName = time() . '_' . basename($_FILES['attachment']['name']);
            $targetFilePath = $uploadDir . $fileName;
            $fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
            
            // Validate file type
            $allowedTypes = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'jpg', 'jpeg', 'png'];
            if (in_array($fileType, $allowedTypes)) {
                if (move_uploaded_file($_FILES['attachment']['tmp_name'], $targetFilePath)) {
                    $attachmentPath = $fileName;
                } else {
                    $error = "Failed to upload file. Please try again.";
                }
            } else {
                $error = "Invalid file type. Allowed types: PDF, DOC, DOCX, XLS, XLSX, JPG, JPEG, PNG.";
            }
        }
        
        if (empty($error)) {
            // Insert report into database
            $sql = "INSERT INTO reports (
                        title, 
                        report_type_id, 
                        level, 
                        level_id, 
                        report_period_start, 
                        report_period_end, 
                        content, 
                        file_path, 
                        status, 
                        submitted_by,
                        user_id,
                        source_type,
                        source_id,
                        target_type,
                        target_id, 
                        created_at
                    ) VALUES (
                        ?, 
                        ?, 
                        ?, 
                        ?, 
                        ?, 
                        ?, 
                        ?, 
                        ?, 
                        'Draft', 
                        ?,
                        ?,
                        ?,
                        ?,
                        ?,
                        ?,
                        NOW()
                    )";
            
            $params = [
                $title,
                $reportTypeId, // Changed from $reportType to $reportTypeId
                $targetType,
                $targetId,
                $reportStartDate,
                $reportEndDate,
                $content,
                $attachmentPath ?: null,
                $userId,
                $userId,
                $userLevel,
                $userEntityId,
                $targetType,
                $targetId
            ];
            
            // Log the SQL query and parameters
            logDebug("Report submission SQL query", [
                'query' => $sql,
                'params' => $params
            ]);
            
            if (executeQuery($sql, $params)) {
                $success = "Report submitted successfully! It will be reviewed by the appropriate authority.";
                logInfo("Report submitted successfully", [
                    'user_id' => $userId,
                    'report_type' => $reportType,
                    'target_type' => $targetType,
                    'target_id' => $targetId
                ]);
            } else {
                $error = "Failed to submit report. Please try again.";
                logError("Report submission failed", [
                    'user_id' => $userId,
                    'report_type' => $reportType,
                    'target_type' => $targetType,
                    'target_id' => $targetId,
                    'sql' => $sql
                ]);
            }
        }
    }
}

// Set base path for includes
$basePath = '..';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Submit Report - GHAMECC Choir Management</title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Summernote CSS -->
    <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.css" rel="stylesheet">
    <!-- Custom CSS -->
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <?php include '../includes/navbar.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include '../includes/sidebar.php'; ?>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Submit Report</h1>
                </div>
                
                <!-- Alert Messages -->
                <?php if ($success): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php echo $success; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo $error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <?php if (empty($targetLevels)): ?>
                    <div class="alert alert-warning" role="alert">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Your account is not properly configured to submit reports. Please contact the administrator.
                    </div>
                <?php else: ?>
                    <div class="card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary">Report Submission Form</h6>
                        </div>
                        <div class="card-body">
                            <form method="post" action="" enctype="multipart/form-data">
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label for="report_type" class="form-label">Report Type *</label>
                                        <select class="form-select" id="report_type" name="report_type" required>
                                            <option value="">Select Report Type</option>
                                            <?php foreach ($reportTypes as $key => $label): ?>
                                                <option value="<?php echo $key; ?>"><?php echo $label['name']; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label for="target_level" class="form-label">Submit To *</label>
                                        <select class="form-select" id="target_level" name="target_level" required>
                                            <option value="">Select Target</option>
                                            <?php foreach ($targetLevels as $key => $target): ?>
                                                <option value="<?php echo $key; ?>"><?php echo $target['name']; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="title" class="form-label">Subject *</label>
                                    <input type="text" class="form-control" id="title" name="title" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="content" class="form-label">Report Content *</label>
                                    <textarea class="form-control" id="content" name="content" rows="10" required></textarea>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="attachment" class="form-label">Attachment (Optional)</label>
                                    <input class="form-control" type="file" id="attachment" name="attachment">
                                    <div class="form-text">Allowed file types: PDF, DOC, DOCX, XLS, XLSX, JPG, JPEG, PNG</div>
                                </div>
                                
                                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-paper-plane me-2"></i> Submit Report
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                <?php endif; ?>
            </main>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Summernote JS -->
    <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.js"></script>
    <!-- Custom JS -->
    <script>
        $(document).ready(function() {
            // Initialize Summernote rich text editor
            $('#content').summernote({
                height: 300,
                toolbar: [
                    ['style', ['style']],
                    ['font', ['bold', 'underline', 'clear']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['table', ['table']],
                    ['insert', ['link']],
                    ['view', ['fullscreen', 'codeview', 'help']]
                ]
            });
        });
    </script>
</body>
</html>
