<?php
/**
 * Finance Management
 * GHAMECC Choir Management Platform
 */

// Include necessary files
require_once '../includes/auth.php';
require_once '../config/database.php';

// Require login
requireLogin();

// Set page title and base path for includes
$pageTitle = "Finance Management";
$basePath = '..';

// Get user role and entity IDs
$userRole = $_SESSION['role'] ?? '';
$userSocietyId = $_SESSION['society_id'] ?? null;
$userCircuitId = $_SESSION['circuit_id'] ?? null;
$userDioceseId = $_SESSION['diocese_id'] ?? null;

// Initialize variables
$societies = [];
$transactions = [];
$financialSummary = [];
$message = '';
$error = '';

// Process form submission for recording financial transaction
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['record_transaction'])) {
    $societyId = $_POST['society_id'] ?? '';
    $transactionType = $_POST['transaction_type'] ?? '';
    $amount = $_POST['amount'] ?? '';
    $transactionDate = $_POST['transaction_date'] ?? '';
    $description = $_POST['description'] ?? '';
    $category = $_POST['category'] ?? '';
    
    // Validate input
    if (empty($societyId) || empty($transactionType) || empty($amount) || empty($transactionDate) || empty($category)) {
        $error = "Please fill all required fields.";
    } else {
        // Insert transaction
        $query = "INSERT INTO financial_transactions (society_id, transaction_type, amount, transaction_date, description, category, recorded_by) 
                  VALUES (?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $conn->prepare($query);
        $stmt->bind_param("isdssis", $societyId, $transactionType, $amount, $transactionDate, $description, $category, $_SESSION['user_id']);
        
        if ($stmt->execute()) {
            $message = "Financial transaction recorded successfully.";
        } else {
            $error = "Error recording transaction: " . $conn->error;
        }
        
        $stmt->close();
    }
}

// Get societies based on user role and access level
if ($userRole === 'admin') {
    // Admin can see all societies
    $query = "SELECT id, name FROM societies ORDER BY name";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $result = $stmt->get_result();
    $societies = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} elseif ($userRole === 'diocesan_secretary' && !empty($userDioceseId)) {
    // Diocese secretary can see societies in their diocese
    $query = "SELECT s.id, s.name 
              FROM societies s 
              JOIN circuits c ON s.circuit_id = c.id 
              WHERE c.diocese_id = ? 
              ORDER BY s.name";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $userDioceseId);
    $stmt->execute();
    $result = $stmt->get_result();
    $societies = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} elseif ($userRole === 'circuit_secretary' && !empty($userCircuitId)) {
    // Circuit secretary can see societies in their circuit
    $query = "SELECT id, name FROM societies WHERE circuit_id = ? ORDER BY name";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $userCircuitId);
    $stmt->execute();
    $result = $stmt->get_result();
    $societies = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} elseif (!empty($userSocietyId)) {
    // Society users can only see their own society
    $query = "SELECT id, name FROM societies WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $userSocietyId);
    $stmt->execute();
    $result = $stmt->get_result();
    $societies = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
}

// Get recent transactions
$query = "SELECT ft.id, ft.transaction_date, ft.transaction_type, ft.amount, ft.description, 
          ft.category, s.name as society_name
          FROM financial_transactions ft
          JOIN societies s ON ft.society_id = s.id";

// Add filters based on user role
$whereParams = [];
if ($userRole === 'admin') {
    // No additional filters for admin
} elseif ($userRole === 'diocesan_secretary' && !empty($userDioceseId)) {
    $query .= " JOIN circuits c ON s.circuit_id = c.id WHERE c.diocese_id = ?";
    $whereParams[] = $userDioceseId;
} elseif ($userRole === 'circuit_secretary' && !empty($userCircuitId)) {
    $query .= " WHERE s.circuit_id = ?";
    $whereParams[] = $userCircuitId;
} elseif (!empty($userSocietyId)) {
    $query .= " WHERE ft.society_id = ?";
    $whereParams[] = $userSocietyId;
}

$query .= " ORDER BY ft.transaction_date DESC LIMIT 10";

$stmt = $conn->prepare($query);

// Check if prepare was successful
if (!$stmt) {
    error_log("SQL Prepare Error in finance/index.php: " . $conn->error);
    $transactions = []; // Initialize empty array to prevent further errors
} else {
    // Bind parameters if any
    if (!empty($whereParams)) {
        $types = str_repeat("i", count($whereParams));
        $stmt->bind_param($types, ...$whereParams);
    }

    if ($stmt->execute()) {
        $result = $stmt->get_result();
        $transactions = $result->fetch_all(MYSQLI_ASSOC);
    } else {
        error_log("SQL Execute Error in finance/index.php: " . $stmt->error);
        $transactions = [];
    }
    $stmt->close();
}

// Get financial summary
$summaryQuery = "SELECT 
                s.name as society_name,
                SUM(CASE WHEN ft.transaction_type = 'income' THEN ft.amount ELSE 0 END) as total_income,
                SUM(CASE WHEN ft.transaction_type = 'expense' THEN ft.amount ELSE 0 END) as total_expense,
                SUM(CASE WHEN ft.transaction_type = 'income' THEN ft.amount ELSE -ft.amount END) as balance
                FROM societies s
                LEFT JOIN financial_transactions ft ON s.id = ft.society_id";

// Add filters based on user role
$summaryWhereParams = [];
if ($userRole === 'admin') {
    // No additional filters for admin
} elseif ($userRole === 'diocesan_secretary' && !empty($userDioceseId)) {
    $summaryQuery .= " JOIN circuits c ON s.circuit_id = c.id WHERE c.diocese_id = ?";
    $summaryWhereParams[] = $userDioceseId;
} elseif ($userRole === 'circuit_secretary' && !empty($userCircuitId)) {
    $summaryQuery .= " WHERE s.circuit_id = ?";
    $summaryWhereParams[] = $userCircuitId;
} elseif (!empty($userSocietyId)) {
    $summaryQuery .= " WHERE s.id = ?";
    $summaryWhereParams[] = $userSocietyId;
}

$summaryQuery .= " GROUP BY s.id ORDER BY s.name";

$summaryStmt = $conn->prepare($summaryQuery);

// Check if prepare was successful
if (!$summaryStmt) {
    error_log("SQL Prepare Error in finance/index.php summary query: " . $conn->error);
    $financialSummary = []; // Initialize empty array to prevent further errors
} else {
    // Bind parameters if any
    if (!empty($summaryWhereParams)) {
        $types = str_repeat("i", count($summaryWhereParams));
        $summaryStmt->bind_param($types, ...$summaryWhereParams);
    }

    if ($summaryStmt->execute()) {
        $summaryResult = $summaryStmt->get_result();
        $financialSummary = $summaryResult->fetch_all(MYSQLI_ASSOC);
    } else {
        error_log("SQL Execute Error in finance/index.php summary query: " . $summaryStmt->error);
        $financialSummary = [];
    }
    $summaryStmt->close();
}

// Don't close connection here - it's needed by includes like navbar.php for notifications
// $conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - 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">
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <!-- 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"><?php echo $pageTitle; ?></h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button class="btn btn-sm btn-primary">
                            <i class="fas fa-plus"></i> Add Transaction
                        </button>
                        <button class="btn btn-sm btn-outline-secondary ms-2">
                            <i class="fas fa-download"></i> Export Report
                        </button>
                    </div>
                </div>
                
                <?php if (!empty($message)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php echo $message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <?php if (!empty($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; ?>

                <!-- Financial Summary Cards -->
                <div class="row mb-4">
                    <?php 
                    $totalIncome = 0;
                    $totalExpense = 0;
                    $totalBalance = 0;
                    
                    foreach ($financialSummary as $summary) {
                        $totalIncome += $summary['total_income'] ?? 0;
                        $totalExpense += $summary['total_expense'] ?? 0;
                        $totalBalance += $summary['balance'] ?? 0;
                    }
                    ?>
                    
                    <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">
                                            Total Income
                                        </div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                                            GH₵ <?php echo number_format($totalIncome, 2); ?>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-arrow-up fa-2x text-success"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card border-left-danger 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-danger text-uppercase mb-1">
                                            Total Expenses
                                        </div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                                            GH₵ <?php echo number_format($totalExpense, 2); ?>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-arrow-down fa-2x text-danger"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <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">
                                            Net Balance
                                        </div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                                            GH₵ <?php echo number_format($totalBalance, 2); ?>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-balance-scale fa-2x text-info"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <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">
                                            Societies
                                        </div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                                            <?php echo count($societies); ?>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-church fa-2x text-warning"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
</body>
</html>
