<?php
require_once '../config/database.php';
require_once '../includes/auth.php';
require_once '../config/logger.php';

// Check if user is logged in
if (!isLoggedIn()) {
    header("Location: ../login.php");
    exit;
}

// Check if user has appropriate role
$allowedRoles = ['circuit_chairman', 'circuit_secretary', 'circuit_dom', 'circuit_treasurer'];
if (!in_array($_SESSION['role'], $allowedRoles)) {
    logWarning("Unauthorized access attempt to circuit dashboard", [
        'user_id' => $_SESSION['user_id'],
        'role' => $_SESSION['role']
    ]);
    header("Location: ../index.php");
    exit;
}

// Get circuit information
$circuitId = $_SESSION['circuit_id'] ?? null;
$circuit = null;

if ($circuitId) {
    // Get circuit details from database
    $stmt = $conn->prepare("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 = ?");
    $stmt->bind_param("i", $circuitId);
    $stmt->execute();
    $result = $stmt->get_result();
    $circuit = $result->fetch_assoc();
    $stmt->close();
    
    logInfo("Circuit dashboard accessed", [
        'user_id' => $_SESSION['user_id'],
        'circuit_id' => $circuitId,
        'found_circuit' => !empty($circuit) ? 'yes' : 'no'
    ]);
} else {
    // Try to get circuit ID from user record
    $userId = $_SESSION['user_id'];
    $stmt = $conn->prepare("SELECT circuit_id FROM users WHERE id = ?");
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();
    
    if ($user && $user['circuit_id']) {
        $circuitId = $user['circuit_id'];
        $_SESSION['circuit_id'] = $circuitId;
        
        // Get circuit details
        $stmt = $conn->prepare("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 = ?");
        $stmt->bind_param("i", $circuitId);
        $stmt->execute();
        $result = $stmt->get_result();
        $circuit = $result->fetch_assoc();
        $stmt->close();
        
        logInfo("Circuit dashboard accessed (circuit_id from user record)", [
            'user_id' => $_SESSION['user_id'],
            'circuit_id' => $circuitId,
            'found_circuit' => !empty($circuit) ? 'yes' : 'no'
        ]);
    } else {
        // Try to get circuit ID from member association
        $stmt = $conn->prepare("SELECT c.* 
                               FROM members m
                               JOIN societies s ON m.society_id = s.id
                               JOIN circuits c ON s.circuit_id = c.id
                               JOIN users u ON m.id = u.member_id
                               WHERE u.id = ?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        $circuitInfo = $result->fetch_assoc();
        $stmt->close();
        
        if ($circuitInfo) {
            $circuitId = $circuitInfo['id'];
            $_SESSION['circuit_id'] = $circuitId;
            
            // Update user record with circuit_id
            $stmt = $conn->prepare("UPDATE users SET circuit_id = ? WHERE id = ?");
            $stmt->bind_param("ii", $circuitId, $userId);
            $stmt->execute();
            $stmt->close();
            
            // Get circuit details
            $stmt = $conn->prepare("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 = ?");
            $stmt->bind_param("i", $circuitId);
            $stmt->execute();
            $result = $stmt->get_result();
            $circuit = $result->fetch_assoc();
            $stmt->close();
            
            logInfo("Circuit dashboard accessed (circuit_id from member association)", [
                'user_id' => $_SESSION['user_id'],
                'circuit_id' => $circuitId,
                'found_circuit' => !empty($circuit) ? 'yes' : 'no'
            ]);
        } else {
            logError("Circuit user without circuit association", [
                'user_id' => $_SESSION['user_id'],
                'role' => $_SESSION['role']
            ]);
        }
    }
}

// If circuit not found, show error
if (!$circuit) {
    $_SESSION['alert_type'] = 'danger';
    $_SESSION['alert_message'] = 'Your account is not properly configured. Please contact the administrator.';
    header("Location: ../index.php");
    exit;
}

$pageTitle = $circuit['name'] . " Circuit Dashboard";
?>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800"><?php echo $circuit['name']; ?> Circuit Dashboard</h1>
    
    <div class="row">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                Diocese</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $circuit['diocese_name']; ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-cathedral fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Societies Count Card -->
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                Societies</div>
                            <?php
                            // Get societies count
                            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM societies WHERE circuit_id = ?");
                            $stmt->bind_param("i", $circuitId);
                            $stmt->execute();
                            $societiesCount = $stmt->get_result()->fetch_assoc()['count'];
                            $stmt->close();
                            ?>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $societiesCount; ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-church fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Members Count Card -->
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                Members</div>
                            <?php
                            // Get member count
                            $stmt = $conn->prepare("SELECT COUNT(*) as count 
                                                  FROM members m
                                                  JOIN societies s ON m.society_id = s.id
                                                  WHERE s.circuit_id = ?");
                            $stmt->bind_param("i", $circuitId);
                            $stmt->execute();
                            $memberCount = $stmt->get_result()->fetch_assoc()['count'];
                            $stmt->close();
                            ?>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $memberCount; ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-users fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Pending Reports Card -->
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                Pending Reports</div>
                            <?php
                            // Get pending reports count
                            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM reports 
                                                  WHERE target_entity_id = ? AND target_entity_type = 'circuit' 
                                                  AND status = 'submitted'");
                            $stmt->bind_param("i", $circuitId);
                            $stmt->execute();
                            $pendingReports = $stmt->get_result()->fetch_assoc()['count'];
                            $stmt->close();
                            ?>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $pendingReports; ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-clipboard-list fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Societies List -->
    <div class="row">
        <div class="col-lg-6">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Societies in <?php echo $circuit['name']; ?> Circuit</h6>
                </div>
                <div class="card-body">
                    <?php
                    // Get societies
                    $stmt = $conn->prepare("SELECT * FROM societies WHERE circuit_id = ? ORDER BY name");
                    $stmt->bind_param("i", $circuitId);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    
                    if ($result->num_rows > 0) {
                        echo '<ul class="list-group">';
                        while ($society = $result->fetch_assoc()) {
                            echo '<li class="list-group-item d-flex justify-content-between align-items-center">';
                            echo htmlspecialchars($society['name']);
                            
                            // Get member count for this society
                            $memberStmt = $conn->prepare("SELECT COUNT(*) as count FROM members WHERE society_id = ?");
                            $memberStmt->bind_param("i", $society['id']);
                            $memberStmt->execute();
                            $memberCount = $memberStmt->get_result()->fetch_assoc()['count'];
                            $memberStmt->close();
                            
                            echo '<span class="badge badge-primary badge-pill">' . $memberCount . ' members</span>';
                            echo '</li>';
                        }
                        echo '</ul>';
                    } else {
                        echo '<p>No societies found in this circuit.</p>';
                    }
                    $stmt->close();
                    ?>
                </div>
            </div>
        </div>

        <div class="col-lg-6">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Recent Reports</h6>
                </div>
                <div class="card-body">
                    <?php
                    // Get recent reports
                    $stmt = $conn->prepare("SELECT r.*, rt.name as report_type_name, u.full_name as submitted_by_name,
                                          s.name as society_name 
                                          FROM reports r
                                          JOIN report_types rt ON r.report_type_id = rt.id
                                          JOIN users u ON r.submitted_by = u.id
                                          JOIN societies s ON r.source_entity_id = s.id AND r.source_entity_type = 'society'
                                          WHERE s.circuit_id = ? AND r.target_entity_id = ? AND r.target_entity_type = 'circuit'
                                          ORDER BY r.submission_date DESC LIMIT 5");
                    $stmt->bind_param("ii", $circuitId, $circuitId);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    
                    if ($result->num_rows > 0) {
                        echo '<ul class="list-group">';
                        while ($report = $result->fetch_assoc()) {
                            echo '<li class="list-group-item">';
                            echo '<div class="d-flex w-100 justify-content-between">';
                            echo '<h5 class="mb-1">' . htmlspecialchars($report['report_type_name']) . '</h5>';
                            echo '<small>' . date('M d, Y', strtotime($report['submission_date'])) . '</small>';
                            echo '</div>';
                            echo '<p class="mb-1">From: ' . htmlspecialchars($report['society_name']) . ' Society</p>';
                            echo '<p class="mb-1">Status: <span class="badge badge-' . 
                                 ($report['status'] == 'approved' ? 'success' : 
                                 ($report['status'] == 'rejected' ? 'danger' : 'warning')) . 
                                 '">' . ucfirst($report['status']) . '</span></p>';
                            echo '<small>Submitted by: ' . htmlspecialchars($report['submitted_by_name']) . '</small>';
                            echo '</li>';
                        }
                        echo '</ul>';
                    } else {
                        echo '<p>No recent reports found.</p>';
                    }
                    $stmt->close();
                    ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include_once '../includes/footer.php'; ?>
