<?php
session_start();
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
}

// Check if user has permission to create funds (Admin or Fund Manager)
if (!in_array($role_name, ['Administrator', 'Fund Manager'])) {
    header('Location: index.php');
    exit();
}

// Handle form submission
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fund_name = trim($_POST['fund_name']);
    $fund_code = trim($_POST['fund_code']);
    $category_id = $_POST['category_id'];
    $description = trim($_POST['description']);
    $purpose = trim($_POST['purpose']);
    $target_amount = !empty($_POST['target_amount']) ? floatval($_POST['target_amount']) : null;
    $start_date = !empty($_POST['start_date']) ? $_POST['start_date'] : null;
    $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
    $fund_manager = $_POST['fund_manager'];
    $status = $_POST['status'];
    $notes = trim($_POST['notes']);
    
    // Validation
    $errors = [];
    
    if (empty($fund_name)) {
        $errors[] = "Fund name is required";
    }
    
    if (empty($fund_code)) {
        $errors[] = "Fund code is required";
    } else {
        // Check if fund code already exists
        $check_code = $conn->prepare("SELECT fund_id FROM funds WHERE fund_code = ?");
        $check_code->bind_param("s", $fund_code);
        $check_code->execute();
        if ($check_code->get_result()->num_rows > 0) {
            $errors[] = "Fund code already exists";
        }
    }
    
    if (empty($category_id)) {
        $errors[] = "Category is required";
    }
    
    if (!empty($end_date) && !empty($start_date) && $end_date <= $start_date) {
        $errors[] = "End date must be after start date";
    }
    
    if (empty($errors)) {
        // Generate fund code if not provided
        if (empty($fund_code)) {
            $fund_code = strtoupper(substr($fund_name, 0, 3)) . date('Y') . sprintf('%03d', rand(1, 999));
        }
        
        try {
            $conn->begin_transaction();
            
            // Insert fund
            $insert_query = "INSERT INTO funds (
                fund_name, fund_code, category_id, description, purpose, 
                target_amount, start_date, end_date, fund_manager, status, notes
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($insert_query);
            $stmt->bind_param("ssissississ", 
                $fund_name, $fund_code, $category_id, $description, $purpose,
                $target_amount, $start_date, $end_date, $fund_manager, $status, $notes
            );
            
            if ($stmt->execute()) {
                $fund_id = $conn->insert_id;
                
                // Log activity
                $activity_query = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values, ip_address) 
                                   VALUES (?, 'CREATE', 'FUNDS', ?, 'FUND', ?, ?)";
                $activity_stmt = $conn->prepare($activity_query);
                $new_values = json_encode([
                    'fund_name' => $fund_name,
                    'fund_code' => $fund_code,
                    'category_id' => $category_id,
                    'target_amount' => $target_amount,
                    'status' => $status
                ]);
                $ip_address = $_SERVER['REMOTE_ADDR'];
                $activity_stmt->bind_param("iiss", $user_id, $fund_id, $new_values, $ip_address);
                $activity_stmt->execute();
                
                $conn->commit();
                
                $message = "Fund '$fund_name' created successfully!";
                $message_type = "success";
                
                // Optionally redirect to fund list or fund details
                // header("Location: list_funds.php");
                // exit();
                
            } else {
                throw new Exception("Error creating fund: " . $conn->error);
            }
            
        } catch (Exception $e) {
            $conn->rollback();
            $message = "Error: " . $e->getMessage();
            $message_type = "error";
        }
    } else {
        $message = implode(", ", $errors);
        $message_type = "error";
    }
}

// Get fund categories
$categories_query = "SELECT category_id, category_name, color_code FROM fund_categories WHERE is_active = 1 ORDER BY category_name";
$categories_result = $conn->query($categories_query);

// Get potential fund managers (Admin and Fund Manager roles)
$managers_query = "SELECT u.user_id, u.full_name, ur.role_name 
                   FROM users u 
                   JOIN user_roles ur ON u.role_id = ur.role_id 
                   WHERE ur.role_name IN ('Administrator', 'Fund Manager') 
                   AND u.status = 'ACTIVE' 
                   ORDER BY u.full_name";
$managers_result = $conn->query($managers_query);

// Get system statistics for context
$stats_query = "SELECT 
    COUNT(*) as total_funds,
    SUM(current_balance) as total_balance,
    COUNT(DISTINCT category_id) as categories_used
    FROM funds 
    WHERE is_active = 1";
$stats = $conn->query($stats_query)->fetch_assoc();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create Fund - Personal Fund Tracker')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        /* Use the same styling from list_consultations.php */
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        /* Breadcrumb */
        .breadcrumb-card {
            background: white;
            border-radius: 8px;
            padding: 1rem 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .breadcrumb {
            margin: 0;
            background: none;
            padding: 0;
        }
        
        .breadcrumb-item a {
            color: #3b82f6;
            text-decoration: none;
        }
        
        .breadcrumb-item.active {
            color: #64748b;
        }
        
        /* Alert Messages */
        .alert {
            border-radius: 8px;
            border: none;
            margin-bottom: 1.5rem;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
        }
        
        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
        }
        
        /* Stats Cards */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        /* Form Card */
        .form-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .form-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .form-section {
            margin-bottom: 2rem;
        }
        
        .section-title {
            font-size: 1rem;
            font-weight: 600;
            color: #374151;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .section-title i {
            color: #059669;
        }
        
        /* Form Controls */
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .form-control, .form-select, .form-control:focus, .form-select:focus {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            outline: none;
        }
        
        .form-text {
            color: #64748b;
            font-size: 0.75rem;
            margin-top: 0.25rem;
        }
        
        /* Required field indicator */
        .required {
            color: #dc2626;
        }
        
        /* Buttons */
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .btn-success {
            background: #059669;
            color: white;
        }
        
        .btn-success:hover {
            background: #047857;
            color: white;
        }
        
        .btn-outline-secondary {
            background: transparent;
            border: 1px solid #e2e8f0;
            color: #64748b;
        }
        
        .btn-outline-secondary:hover {
            background: #f8fafc;
            border-color: #64748b;
        }
        
        .btn-primary {
            background: #3b82f6;
            color: white;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
            color: white;
        }
        
        /* Category Preview */
        .category-preview {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem;
            border-radius: 4px;
            background: #f8fafc;
            margin-top: 0.5rem;
        }
        
        .category-color {
            width: 16px;
            height: 16px;
            border-radius: 3px;
            border: 1px solid rgba(0, 0, 0, 0.1);
        }
        
        /* Input Groups */
        .input-group-text {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            color: #64748b;
            font-weight: 500;
        }
        
        /* Grid Layout */
        .grid-2 {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 2rem;
        }
        
        /* Button Group */
        .button-group {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            padding-top: 1.5rem;
            border-top: 1px solid #e2e8f0;
            margin-top: 2rem;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .grid-2 {
                grid-template-columns: 1fr;
            }
            
            .button-group {
                flex-direction: column;
            }
            
            .form-card {
                padding: 1.5rem;
            }
        }
        
        /* Footer spacing fix */
        .main-content {
            padding-bottom: 2rem;
        }
        
        .page-content {
            margin-bottom: 3rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <h1 class="page-title">Create New Fund</h1>
                        <p class="page-subtitle">Set up a new fund for collecting and managing contributions</p>
                    </div>

                    <!-- Breadcrumb -->
                    <div class="breadcrumb-card">
                        <nav aria-label="breadcrumb">
                            <ol class="breadcrumb">
                                <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                <li class="breadcrumb-item"><a href="list_funds.php">All Funds</a></li>
                                <li class="breadcrumb-item active">Create Fund</li>
                            </ol>
                        </nav>
                    </div>

                    <!-- Alert Messages -->
                    <?php if ($message): ?>
                        <div class="alert alert-<?php echo $message_type === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show" role="alert">
                            <?php echo htmlspecialchars($message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Current System Stats -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['total_funds'] ?? 0; ?></div>
                            <div class="stat-label">Existing Funds</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['total_balance'] ?? 0); ?></div>
                            <div class="stat-label">Total Balance</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['categories_used'] ?? 0; ?></div>
                            <div class="stat-label">Categories in Use</div>
                        </div>
                    </div>

                    <!-- Create Fund Form -->
                    <div class="form-card">
                        <h3 class="form-title">Fund Information</h3>
                        
                        <form method="POST" id="createFundForm">
                            <!-- Basic Information Section -->
                            <div class="form-section">
                                <h4 class="section-title">
                                    <i class="ph-info"></i>
                                    Basic Information
                                </h4>
                                
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Fund Name <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="fund_name" required 
                                               placeholder="e.g., Emergency Medical Fund" 
                                               value="<?php echo htmlspecialchars($_POST['fund_name'] ?? ''); ?>">
                                        <div class="form-text">Choose a descriptive name for your fund</div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Fund Code <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="fund_code" required 
                                               placeholder="e.g., EMF2025001" 
                                               value="<?php echo htmlspecialchars($_POST['fund_code'] ?? ''); ?>"
                                               style="text-transform: uppercase;">
                                        <div class="form-text">Unique identifier for the fund</div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Category <span class="required">*</span></label>
                                        <select class="form-select" name="category_id" required id="categorySelect">
                                            <option value="">Select a category</option>
                                            <?php while ($category = $categories_result->fetch_assoc()): ?>
                                                <option value="<?php echo $category['category_id']; ?>" 
                                                        data-color="<?php echo $category['color_code']; ?>"
                                                        <?php echo (($_POST['category_id'] ?? '') == $category['category_id']) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($category['category_name']); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                        <div id="categoryPreview" class="category-preview" style="display: none;">
                                            <div class="category-color" id="previewColor"></div>
                                            <span id="previewName"></span>
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Fund Manager</label>
                                        <select class="form-select" name="fund_manager">
                                            <option value="">Select a manager (optional)</option>
                                            <?php while ($manager = $managers_result->fetch_assoc()): ?>
                                                <option value="<?php echo $manager['user_id']; ?>"
                                                        <?php echo (($_POST['fund_manager'] ?? '') == $manager['user_id']) ? 'selected' : ''; ?>
                                                        <?php echo $manager['user_id'] == $user_id ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($manager['full_name']); ?> (<?php echo $manager['role_name']; ?>)
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                        <div class="form-text">Person responsible for managing this fund</div>
                                    </div>
                                    
                                    <div class="col-12">
                                        <label class="form-label">Description</label>
                                        <textarea class="form-control" name="description" rows="3" 
                                                  placeholder="Brief description of the fund's purpose and goals"><?php echo htmlspecialchars($_POST['description'] ?? ''); ?></textarea>
                                    </div>
                                    
                                    <div class="col-12">
                                        <label class="form-label">Purpose</label>
                                        <textarea class="form-control" name="purpose" rows="3" 
                                                  placeholder="Detailed purpose and intended use of the fund"><?php echo htmlspecialchars($_POST['purpose'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                            </div>

                            <!-- Financial & Timeline Section -->
                            <div class="form-section">
                                <h4 class="section-title">
                                    <i class="ph-calendar"></i>
                                    Financial & Timeline Settings
                                </h4>
                                
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Target Amount</label>
                                        <div class="input-group">
                                            <span class="input-group-text">KES</span>
                                            <input type="number" class="form-control" name="target_amount" min="0" step="0.01"
                                                   placeholder="0.00" value="<?php echo htmlspecialchars($_POST['target_amount'] ?? ''); ?>">
                                        </div>
                                        <div class="form-text">Optional: Set a target amount to reach</div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Status</label>
                                        <select class="form-select" name="status">
                                            <option value="ACTIVE" <?php echo (($_POST['status'] ?? 'ACTIVE') == 'ACTIVE') ? 'selected' : ''; ?>>Active</option>
                                            <option value="SUSPENDED" <?php echo (($_POST['status'] ?? '') == 'SUSPENDED') ? 'selected' : ''; ?>>Suspended</option>
                                        </select>
                                        <div class="form-text">Initial status of the fund</div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Start Date</label>
                                        <input type="date" class="form-control" name="start_date" 
                                               value="<?php echo htmlspecialchars($_POST['start_date'] ?? date('Y-m-d')); ?>">
                                        <div class="form-text">When the fund becomes active</div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">End Date</label>
                                        <input type="date" class="form-control" name="end_date" 
                                               value="<?php echo htmlspecialchars($_POST['end_date'] ?? ''); ?>">
                                        <div class="form-text">Optional: When the fund should close</div>
                                    </div>
                                </div>
                            </div>

                            <!-- Additional Notes Section -->
                            <div class="form-section">
                                <h4 class="section-title">
                                    <i class="ph-note"></i>
                                    Additional Notes
                                </h4>
                                
                                <div class="row g-3">
                                    <div class="col-12">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="notes" rows="4" 
                                                  placeholder="Any additional notes, rules, or special instructions for this fund"><?php echo htmlspecialchars($_POST['notes'] ?? ''); ?></textarea>
                                        <div class="form-text">Internal notes about the fund (not visible to contributors)</div>
                                    </div>
                                </div>
                            </div>

                            <!-- Form Buttons -->
                            <div class="button-group">
                                <a href="list_funds.php" class="btn btn-outline-secondary">
                                    <i class="ph-x"></i> Cancel
                                </a>
                                <button type="submit" class="btn btn-success">
                                    <i class="ph-plus"></i> Create Fund
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Category selection preview
            $('#categorySelect').on('change', function() {
                const selectedOption = $(this).find('option:selected');
                const color = selectedOption.data('color');
                const name = selectedOption.text();
                
                if (selectedOption.val()) {
                    $('#previewColor').css('background-color', color);
                    $('#previewName').text(name);
                    $('#categoryPreview').show();
                } else {
                    $('#categoryPreview').hide();
                }
            });
            
            // Auto-generate fund code based on name
            $('input[name="fund_name"]').on('input', function() {
                const fundName = $(this).val();
                const fundCodeInput = $('input[name="fund_code"]');
                
                if (fundName && !fundCodeInput.val()) {
                    // Generate code: First 3 letters + Year + 3 digit number
                    const initials = fundName.split(' ').map(word => word.charAt(0)).join('').toUpperCase().substring(0, 3);
                    const year = new Date().getFullYear();
                    const randomNum = Math.floor(Math.random() * 900) + 100; // 3 digit number
                    const suggestedCode = initials + year + randomNum;
                    
                    fundCodeInput.val(suggestedCode);
                }
            });
            
            // Form validation
            $('#createFundForm').on('submit', function(e) {
                const startDate = $('input[name="start_date"]').val();
                const endDate = $('input[name="end_date"]').val();
                
                if (startDate && endDate && new Date(endDate) <= new Date(startDate)) {
                    e.preventDefault();
                    alert('End date must be after start date');
                    return false;
                }
                
                // Show loading state
                $(this).find('button[type="submit"]').prop('disabled', true).html('<i class="ph-spinner ph-spin"></i> Creating Fund...');
            });
            
            // Initialize category preview if already selected
            const initialCategory = $('#categorySelect').find('option:selected');
            if (initialCategory.val()) {
                $('#previewColor').css('background-color', initialCategory.data('color'));
                $('#previewName').text(initialCategory.text());
                $('#categoryPreview').show();
            }
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>

<?php $conn->close(); ?>