<?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 = ['diocesan_chairman', 'diocesan_secretary', 'diocesan_dom', 'diocesan_treasurer'];
if (!in_array($_SESSION['role'], $allowedRoles)) {
    logWarning("Unauthorized access attempt to diocese dashboard", [
        'user_id' => $_SESSION['user_id'],
        'role' => $_SESSION['role']
    ]);
    header("Location: ../index.php");
    exit;
}

// Get diocese information
$dioceseId = $_SESSION['diocese_id'] ?? null;
$diocese = null;

if ($dioceseId) {
    // Get diocese details from database
    $stmt = $conn->prepare("SELECT * FROM dioceses WHERE id = ?");
    $stmt->bind_param("i", $dioceseId);
    $stmt->execute();
    $result = $stmt->get_result();
    $diocese = $result->fetch_assoc();
    $stmt->close();
    
    logInfo("Diocese dashboard accessed", [
        'user_id' => $_SESSION['user_id'],
        'diocese_id' => $dioceseId,
        'found_diocese' => !empty($diocese) ? 'yes' : 'no'
    ]);
} else {
    // Try to get diocese ID from user record
    $userId = $_SESSION['user_id'];
    $stmt = $conn->prepare("SELECT diocese_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['diocese_id']) {
        $dioceseId = $user['diocese_id'];
        $_SESSION['diocese_id'] = $dioceseId;
        
        // Get diocese details
        $stmt = $conn->prepare("SELECT * FROM dioceses WHERE id = ?");
        $stmt->bind_param("i", $dioceseId);
        $stmt->execute();
        $result = $stmt->get_result();
        $diocese = $result->fetch_assoc();
        $stmt->close();
        
        logInfo("Diocese dashboard accessed (diocese_id from user record)", [
            'user_id' => $_SESSION['user_id'],
            'diocese_id' => $dioceseId,
            'found_diocese' => !empty($diocese) ? 'yes' : 'no'
        ]);
    } else {
        // Try to get diocese ID from member association
        $stmt = $conn->prepare("SELECT d.* 
                               FROM members m
                               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
                               JOIN users u ON m.id = u.member_id
                               WHERE u.id = ?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        $dioceseInfo = $result->fetch_assoc();
        $stmt->close();
        
        if ($dioceseInfo) {
            $dioceseId = $dioceseInfo['id'];
            $_SESSION['diocese_id'] = $dioceseId;
            
            // Update user record with diocese_id
            $stmt = $conn->prepare("UPDATE users SET diocese_id = ? WHERE id = ?");
            $stmt->bind_param("ii", $dioceseId, $userId);
            $stmt->execute();
            $stmt->close();
            
            // Get diocese details
            $stmt = $conn->prepare("SELECT * FROM dioceses WHERE id = ?");
            $stmt->bind_param("i", $dioceseId);
            $stmt->execute();
            $result = $stmt->get_result();
            $diocese = $result->fetch_assoc();
            $stmt->close();
            
            logInfo("Diocese dashboard accessed (diocese_id from member association)", [
                'user_id' => $_SESSION['user_id'],
                'diocese_id' => $dioceseId,
                'found_diocese' => !empty($diocese) ? 'yes' : 'no'
            ]);
        } else {
            logError("Diocese user without diocese association", [
                'user_id' => $_SESSION['user_id'],
                'role' => $_SESSION['role']
            ]);
        }
    }
}

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

$pageTitle = $diocese['name'] . " Diocese Dashboard";
include_once '../includes/header.php';
?>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800"><?php echo $diocese['name']; ?> Diocese Dashboard</h1>
    
    <div class="row">
        <!-- Circuits Count Card -->
        <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">
                                Circuits</div>
                            <?php
                            // Get circuits count
                            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM circuits WHERE diocese_id = ?");
                            $stmt->bind_param("i", $dioceseId);
                            $stmt->execute();
                            $circuitsCount = $stmt->get_result()->fetch_assoc()['count'];
                            $stmt->close();
                            ?>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $circuitsCount; ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-church 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 s
                                                  JOIN circuits c ON s.circuit_id = c.id
                                                  WHERE c.diocese_id = ?");
                            $stmt->bind_param("i", $dioceseId);
                            $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-building 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
                                                  JOIN circuits c ON s.circuit_id = c.id
                                                  WHERE c.diocese_id = ?");
                            $stmt->bind_param("i", $dioceseId);
                            $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 = 'diocese' 
                                                  AND status = 'submitted'");
                            $stmt->bind_param("i", $dioceseId);
                            $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>

    <!-- Circuits 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">Circuits in <?php echo $diocese['name']; ?> Diocese</h6>
                </div>
                <div class="card-body">
                    <?php
                    // Get circuits
                    $stmt = $conn->prepare("SELECT c.*, 
                                          (SELECT COUNT(*) FROM societies s WHERE s.circuit_id = c.id) as society_count
                                          FROM circuits c 
                                          WHERE c.diocese_id = ? 
                                          ORDER BY c.name");
                    $stmt->bind_param("i", $dioceseId);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    
                    if ($result->num_rows > 0) {
                        echo '<ul class="list-group">';
                        while ($circuit = $result->fetch_assoc()) {
                            echo '<li class="list-group-item d-flex justify-content-between align-items-center">';
                            echo htmlspecialchars($circuit['name']);
                            echo '<span class="badge badge-primary badge-pill">' . $circuit['society_count'] . ' societies</span>';
                            echo '</li>';
                        }
                        echo '</ul>';
                    } else {
                        echo '<p>No circuits found in this diocese.</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,
                                          c.name as circuit_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 circuits c ON r.source_entity_id = c.id AND r.source_entity_type = 'circuit'
                                          WHERE c.diocese_id = ? AND r.target_entity_id = ? AND r.target_entity_type = 'diocese'
                                          ORDER BY r.submission_date DESC LIMIT 5");
                    $stmt->bind_param("ii", $dioceseId, $dioceseId);
                    $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['circuit_name']) . ' Circuit</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'; ?>
