<?php
session_start();
require_once __DIR__ . '/../../classes/Logger.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Expense.php';
require_once __DIR__ . '/../../classes/Branch.php';


$database = new Database();
$conn = $database->getConnection();


$auth = new Auth($conn);


if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}
$auth->enforceSuperAdminPrivileges($_SESSION['user_id']);


$expense = new Expense($conn);
$branch = new Branch($conn);
$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);



$categories = $expense->getAllCategories()->fetchAll(PDO::FETCH_ASSOC);


$branches = $branch->getAllBranches();
$expense = new Expense($conn, $logger);


$expense_category_id = '';
$description = '';
$amount = '';
$expense_date = date('Y-m-d');
$branch_id = '';
$errors = [];
$success_message = $_SESSION['expense_success_message'] ?? '';
unset($_SESSION['expense_success_message']);
$duplicate_source_month = $_POST['source_month'] ?? date('Y-m', strtotime('first day of last month'));
$duplicate_target_month = $_POST['target_month'] ?? date('Y-m');
$duplicate_category_ids = isset($_POST['category_ids'])
    ? array_values(array_unique(array_filter(array_map('intval', (array) $_POST['category_ids']))))
    : array_map('intval', array_column($categories, 'category_id'));

if (empty($_SESSION['expense_form_csrf'])) {
    $_SESSION['expense_form_csrf'] = bin2hex(random_bytes(32));
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $form_action = $_POST['form_action'] ?? 'add_expense';
    $csrf_token = $_POST['csrf_token'] ?? '';

    if (!hash_equals($_SESSION['expense_form_csrf'], $csrf_token)) {
        $errors[] = 'Your form session expired. Please refresh the page and try again.';
    }

    if ($form_action === 'duplicate_month') {
        $duplicate_source_month = trim($_POST['source_month'] ?? '');
        $duplicate_target_month = trim($_POST['target_month'] ?? '');
        $duplicate_category_ids = array_values(array_unique(array_filter(array_map(
            'intval',
            (array) ($_POST['category_ids'] ?? [])
        ))));

        if (!preg_match('/^\d{4}-\d{2}$/', $duplicate_source_month)) {
            $errors[] = 'Select a valid source month.';
        }
        if (!preg_match('/^\d{4}-\d{2}$/', $duplicate_target_month)) {
            $errors[] = 'Select a valid destination month.';
        }
        if ($duplicate_source_month === $duplicate_target_month) {
            $errors[] = 'Source and destination months must be different.';
        }
        if (empty($duplicate_category_ids)) {
            $errors[] = 'Select at least one expense category to duplicate.';
        } else {
            $validCategoryIds = array_map('intval', array_column($categories, 'category_id'));
            if (array_diff($duplicate_category_ids, $validCategoryIds)) {
                $errors[] = 'One or more selected expense categories are invalid.';
            }
        }

        if (empty($errors)) {
            try {
                $duplicatedCount = $expense->duplicateMonth(
                    $duplicate_source_month,
                    $duplicate_target_month,
                    $_SESSION['user_id'],
                    $duplicate_category_ids
                );

                if ($duplicatedCount === 0) {
                    $errors[] = 'No expenses were found in the selected source month.';
                } else {
                    $_SESSION['expense_success_message'] = sprintf(
                        '%d expense%s duplicated from %s to %s.',
                        $duplicatedCount,
                        $duplicatedCount === 1 ? '' : 's',
                        date('F Y', strtotime($duplicate_source_month . '-01')),
                        date('F Y', strtotime($duplicate_target_month . '-01'))
                    );
                    header('Location: add_expense.php');
                    exit();
                }
            } catch (Throwable $e) {
                error_log('Expense month duplication failed: ' . $e->getMessage());
                $errors[] = 'Failed to duplicate the selected month. Please try again.';
            }
        }
    } else {

    $expense_category_id = trim($_POST['expense_category_id'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $amount = trim($_POST['amount'] ?? '');
    $expense_date = trim($_POST['expense_date'] ?? '');
    $branch_id = trim($_POST['branch_id'] ?? '');


    if (empty($expense_category_id)) {
        $errors[] = 'Expense category is required';
    }

    if (empty($description)) {
        $errors[] = 'Description is required';
    }

    if (empty($amount)) {
        $errors[] = 'Amount is required';
    } elseif (!is_numeric($amount) || $amount <= 0) {
        $errors[] = 'Amount must be a positive number';
    }

    if (empty($expense_date)) {
        $errors[] = 'Expense date is required';
    } elseif (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $expense_date)) {
        $errors[] = 'Expense date must be in YYYY-MM-DD format';
    }


    if (empty($errors)) {
        $expense->expense_category_id = $expense_category_id;
        $expense->description = $description;
        $expense->amount = $amount;
        $expense->expense_date = $expense_date;
        $expense->branch_id = $branch_id ?: null;
        $expense->user_id = $_SESSION['user_id'];

        if ($expense->create()) {
            $success_message = 'Expense added successfully!';

            $expense_category_id = '';
            $description = '';
            $amount = '';
            $expense_date = date('Y-m-d');
            $branch_id = '';
        } else {
            $errors[] = 'Failed to add expense. Please try again.';
        }
    }
    }
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
<style>
    .card {
        margin-bottom: 20px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    .form-group {
        margin-bottom: 1rem;
    }
</style>
    <div class="container mt-4">
        <div class="row mb-3">
            <div class="col-auto">
                <a href="manage_expenses.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Back to Expenses
                </a>
            </div>
        </div>

        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($success_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <ul class="mb-0">
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <div class="card border-info">
            <div class="card-header bg-info text-white">
                <h3 class="mb-0 h5"><i class="fas fa-copy"></i> Duplicate Monthly Expenses</h3>
            </div>
            <div class="card-body">
                <p class="text-muted">
                    Copy every expense from one month into another. Categories, descriptions, amounts, branches,
                    and day-of-month are preserved. Dates beyond the destination month's last day are adjusted automatically.
                </p>
                <form method="post" action="" onsubmit="return confirmDuplicateExpenses();">
                    <input type="hidden" name="form_action" value="duplicate_month">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['expense_form_csrf'], ENT_QUOTES, 'UTF-8'); ?>">
                    <div class="mb-3">
                        <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-2">
                            <label class="form-label mb-0">Categories to Duplicate</label>
                            <div class="btn-group btn-group-sm" role="group" aria-label="Category selection controls">
                                <button type="button" class="btn btn-outline-info" id="selectAllDuplicateCategories">Select All</button>
                                <button type="button" class="btn btn-outline-secondary" id="clearDuplicateCategories">Clear</button>
                            </div>
                        </div>
                        <div class="border rounded p-3">
                            <div class="row g-2">
                                <?php foreach ($categories as $category): ?>
                                    <?php $categoryId = (int) $category['category_id']; ?>
                                    <div class="col-lg-4 col-md-6">
                                        <div class="form-check">
                                            <input class="form-check-input duplicate-category-checkbox" type="checkbox" name="category_ids[]" value="<?php echo $categoryId; ?>" id="duplicate_category_<?php echo $categoryId; ?>" <?php echo in_array($categoryId, $duplicate_category_ids, true) ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="duplicate_category_<?php echo $categoryId; ?>">
                                                <?php echo htmlspecialchars($category['category_name']); ?>
                                            </label>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="form-text">Only expenses belonging to the checked categories will be copied.</div>
                    </div>
                    <div class="row g-3 align-items-end">
                        <div class="col-md-4">
                            <label for="source_month" class="form-label">Source Month</label>
                            <input type="month" class="form-control" id="source_month" name="source_month" value="<?php echo htmlspecialchars($duplicate_source_month, ENT_QUOTES, 'UTF-8'); ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label for="target_month" class="form-label">Destination Month</label>
                            <input type="month" class="form-control" id="target_month" name="target_month" value="<?php echo htmlspecialchars($duplicate_target_month, ENT_QUOTES, 'UTF-8'); ?>" required>
                        </div>
                        <div class="col-md-4">
                            <button type="submit" class="btn btn-info text-white w-100">
                                <i class="fas fa-copy"></i> Duplicate Expenses
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-header bg-primary text-white">
                <h2 class="mb-0">Add New Expense</h2>
            </div>
            <div class="card-body">
                <form method="post" action="">
                    <input type="hidden" name="form_action" value="add_expense">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['expense_form_csrf'], ENT_QUOTES, 'UTF-8'); ?>">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="expense_category_id">Expense Category <span class="text-danger">*</span></label>
                                <select class="form-control" id="expense_category_id" name="expense_category_id" required>
                                    <option value="">Select Category</option>
                                    <?php foreach ($categories as $category): ?>
                                        <option value="<?php echo htmlspecialchars($category['category_id']); ?>" <?php echo ($expense_category_id == $category['category_id']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($category['category_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="form-group">
                                <label for="description">Description <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="description" name="description" rows="3" required><?php echo htmlspecialchars($description); ?></textarea>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="amount">Amount <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <span class="input-group-text">$</span>
                                    <input type="number" class="form-control" id="amount" name="amount" step="0.01" min="0.01" value="<?php echo htmlspecialchars($amount); ?>" required>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="expense_date">Expense Date <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" id="expense_date" name="expense_date" value="<?php echo htmlspecialchars($expense_date); ?>" required>
                            </div>

                            <div class="form-group">
                                <label for="branch_id">Branch (Optional)</label>
                                <select class="form-control" id="branch_id" name="branch_id">
                                    <option value="">Select Branch</option>
                                    <?php while ($branch_item = $branches->fetch(PDO::FETCH_ASSOC)): ?>
                                        <option value="<?php echo htmlspecialchars($branch_item['branch_id']); ?>" <?php echo ($branch_id == $branch_item['branch_id']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($branch_item['branch_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="mt-4">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Save Expense
                        </button>
                        <a href="manage_expenses.php" class="btn btn-secondary">
                            <i class="fas fa-times"></i> Cancel
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>

<script>
    const duplicateCategoryCheckboxes = document.querySelectorAll('.duplicate-category-checkbox');
    const selectAllDuplicateCategories = document.getElementById('selectAllDuplicateCategories');
    const clearDuplicateCategories = document.getElementById('clearDuplicateCategories');

    if (selectAllDuplicateCategories) {
        selectAllDuplicateCategories.addEventListener('click', function () {
            duplicateCategoryCheckboxes.forEach(function (checkbox) {
                checkbox.checked = true;
            });
        });
    }

    if (clearDuplicateCategories) {
        clearDuplicateCategories.addEventListener('click', function () {
            duplicateCategoryCheckboxes.forEach(function (checkbox) {
                checkbox.checked = false;
            });
        });
    }

    function confirmDuplicateExpenses() {
        const selectedCount = document.querySelectorAll('.duplicate-category-checkbox:checked').length;
        if (selectedCount === 0) {
            alert('Select at least one expense category to duplicate.');
            return false;
        }

        return confirm(
            'Duplicate expenses from ' + selectedCount +
            ' selected categor' + (selectedCount === 1 ? 'y' : 'ies') +
            ' into the destination month?'
        );
    }
</script>

<?php include __DIR__ . '/../../includes/footer.php'; ?>
