<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../config.php';

if (!isLoggedIn() || !isAdmin()) {
    setMessage('دسترسی غیرمجاز', 'error');
    redirect('../login.php');
}

// Handle Add/Delete Expense
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'add_expense') {
        $expense_type = trim($_POST['expense_type']);
        $amount = (float)trim($_POST['amount']);
        $transaction_date = trim($_POST['transaction_date']);
        $description = trim($_POST['description']);

        if (!empty($expense_type) && $amount > 0 && !empty($transaction_date)) {
            try {
                $stmt = $pdo->prepare("INSERT INTO expenses (expense_type, amount, transaction_date, description) VALUES (?, ?, ?, ?)");
                $stmt->execute([$expense_type, $amount, $transaction_date, $description]);
                setMessage('هزینه با موفقیت ثبت شد.');
            } catch (Exception $e) {
                setMessage('خطا در ثبت هزینه: ' . $e->getMessage(), 'error');
            }
        } else {
            setMessage('لطفاً تمام فیلدهای اجباری را پر کنید.', 'error');
        }
        redirect('financial_reports.php');
    }

    if (isset($_POST['action']) && $_POST['action'] === 'delete_expense') {
        $expense_id = (int)$_POST['expense_id'];
        if ($expense_id > 0) {
            try {
                $stmt = $pdo->prepare("DELETE FROM expenses WHERE id = ?");
                $stmt->execute([$expense_id]);
                setMessage('هزینه با موفقیت حذف شد.');
            } catch (Exception $e) {
                setMessage('خطا در حذف هزینه: ' . $e->getMessage(), 'error');
            }
        }
        redirect('financial_reports.php');
    }
}

$page_title = 'گزارشات مالی';

// Fetch data
$transactions = $pdo->query("SELECT wt.*, r.username, r.full_name FROM wallet_transactions wt JOIN representatives r ON wt.representative_id = r.id ORDER BY wt.created_at DESC")->fetchAll();
$expenses = $pdo->query("SELECT * FROM expenses ORDER BY transaction_date DESC")->fetchAll();

// Calculate stats
$stats = [
    'total_deposits' => 0,
    'total_deductions' => 0,
    'total_expenses' => 0,
    'net_profit' => 0,
    'total_deposits_month' => 0,
    'total_deposits_year' => 0,
];

$current_year = date('Y');
$current_month = date('m');

foreach ($transactions as $tx) {
    if ($tx['amount'] > 0) {
        $stats['total_deposits'] += $tx['amount'];
        $tx_year = date('Y', strtotime($tx['created_at']));
        $tx_month = date('m', strtotime($tx['created_at']));
        if ($tx_year == $current_year) {
            $stats['total_deposits_year'] += $tx['amount'];
            if ($tx_month == $current_month) {
                $stats['total_deposits_month'] += $tx['amount'];
            }
        }
    } else {
        $stats['total_deductions'] += abs($tx['amount']);
    }
}
foreach ($expenses as $ex) {
    $stats['total_expenses'] += $ex['amount'];
}
$stats['net_profit'] = $stats['total_deposits'] - $stats['total_deductions'] - $stats['total_expenses'];

$type_labels = get_type_labels();

require_once '../includes/header.php';
?>

<div class="card admin-main-card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
        <h3 class="card-title mb-0"><?= htmlspecialchars($page_title) ?></h3>
        <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addExpenseModal">
            <i class="bi bi-plus-circle me-1"></i> ثبت هزینه جدید
        </button>
    </div>
    <div class="card-body pb-0">

<!-- Stat Cards -->
<div class="row g-4 mb-4">
    <div class="col-lg-4 col-md-6">
        <div class="stat-card-pro">
            <div class="d-flex align-items-center">
                <div class="stat-icon bg-soft-success text-success me-3"><i class="bi bi-cash-stack"></i></div>
                <div>
                    <div class="stat-label">درآمد کل</div>
                    <div class="stat-value fs-4"><?= number_format($stats['total_deposits']) ?> <small>تومان</small></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-4 col-md-6">
        <div class="stat-card-pro">
            <div class="d-flex align-items-center">
                <div class="stat-icon bg-soft-info text-info me-3"><i class="bi bi-calendar-check"></i></div>
                <div>
                    <div class="stat-label">درآمد این ماه</div>
                    <div class="stat-value fs-4"><?= number_format($stats['total_deposits_month']) ?> <small>تومان</small></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-4 col-md-6">
        <div class="stat-card-pro">
            <div class="d-flex align-items-center">
                <div class="stat-icon bg-soft-primary text-primary me-3"><i class="bi bi-calendar3"></i></div>
                <div>
                    <div class="stat-label">درآمد امسال</div>
                    <div class="stat-value fs-4"><?= number_format($stats['total_deposits_year']) ?> <small>تومان</small></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-4 col-md-6">
        <div class="stat-card-pro">
            <div class="d-flex align-items-center">
                <div class="stat-icon bg-soft-warning text-warning me-3"><i class="bi bi-arrow-up-right-circle"></i></div>
                <div>
                    <div class="stat-label">مصارف کل (شارژ)</div>
                    <div class="stat-value fs-4"><?= number_format($stats['total_deductions']) ?> <small>تومان</small></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-4 col-md-6">
        <div class="stat-card-pro">
            <div class="d-flex align-items-center">
                <div class="stat-icon bg-soft-danger text-danger me-3"><i class="bi bi-cart-x"></i></div>
                <div>
                    <div class="stat-label">هزینه‌های کل</div>
                    <div class="stat-value fs-4"><?= number_format($stats['total_expenses']) ?> <small>تومان</small></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-4 col-md-6">
        <div class="stat-card-pro">
            <div class="d-flex align-items-center">
                <div class="stat-icon bg-soft-primary text-primary me-3"><i class="bi bi-graph-up-arrow"></i></div>
                <div>
                    <div class="stat-label">سود خالص کل</div>
                    <div class="stat-value fs-4"><?= number_format($stats['net_profit']) ?> <small>تومان</small></div>
                </div>
            </div>
        </div>
    </div>
    </div>
    </div>
</div>

<!-- Nav Tabs -->
<ul class="nav nav-tabs nav-fill mb-3" role="tablist">
    <li class="nav-item" role="presentation"><a class="nav-link active" data-bs-toggle="tab" href="#transactions" role="tab">تراکنش‌های کیف پول</a></li>
    <li class="nav-item" role="presentation"><a class="nav-link" data-bs-toggle="tab" href="#expenses" role="tab">هزینه‌های ثبت شده</a></li>
</ul>

<!-- Tab Content -->
<div class="tab-content">
    <div class="tab-pane active" id="transactions" role="tabpanel">
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="transactions-table" class="table table-hover align-middle">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>نماینده</th>
                                <th>نوع تراکنش</th>
                                <th>مبلغ</th>
                                <th>تاریخ</th>
                                <th>توضیحات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($transactions as $tx): ?>
                                <tr>
                                    <td><?= $tx['id'] ?></td>
                                    <td><a href="representative_monitor.php?id=<?= $tx['representative_id'] ?>"><?= htmlspecialchars($tx['full_name'] ?: $tx['username']) ?></a></td>
                                    <td><span class="badge bg-secondary-soft"><?= htmlspecialchars($type_labels[$tx['type']] ?? $tx['type']) ?></span></td>
                                    <td><span class="fw-bold <?= (float)$tx['amount'] >= 0 ? 'text-success' : 'text-danger' ?>"><?= ((float)$tx['amount'] >= 0 ? '+' : '-') . number_format(abs($tx['amount'])) ?></span></td>
                                    <td><?= to_jalali($tx['created_at'], 'Y/m/d H:i') ?></td>
                                    <td><?= htmlspecialchars($tx['description'] ?? '-') ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="tab-pane" id="expenses" role="tabpanel">
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="expenses-table" class="table table-hover align-middle">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>نوع هزینه</th>
                                <th>مبلغ</th>
                                <th>تاریخ</th>
                                <th>توضیحات</th>
                                <th>عملیات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($expenses as $ex): ?>
                                <tr>
                                    <td><?= $ex['id'] ?></td>
                                    <td><?= htmlspecialchars($ex['expense_type']) ?></td>
                                    <td><span class="fw-bold text-danger"><?= number_format($ex['amount']) ?></span></td>
                                    <td><?= to_jalali($ex['transaction_date'], 'Y/m/d') ?></td>
                                    <td><?= htmlspecialchars($ex['description'] ?? '-') ?></td>
                                    <td>
                                        <form method="POST" action="financial_reports.php" onsubmit="return confirm('آیا از حذف این هزینه مطمئن هستید؟');" style="display: inline;">
                                            <input type="hidden" name="action" value="delete_expense">
                                            <input type="hidden" name="expense_id" value="<?= $ex['id'] ?>">
                                            <button type="submit" class="btn btn-icon btn-sm btn-danger"><i class="bi bi-trash"></i></button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Expense Modal -->
<div class="modal fade" id="addExpenseModal" tabindex="-1" aria-labelledby="addExpenseModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form method="POST" action="financial_reports.php">
                <input type="hidden" name="action" value="add_expense">
                <div class="modal-header">
                    <h5 class="modal-title" id="addExpenseModalLabel">ثبت هزینه جدید</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="expense_type" class="form-label">نوع هزینه <span class="text-danger">*</span></label>
                        <select class="form-select" id="expense_type" name="expense_type" required>
                            <option value="" selected disabled>یک مورد را انتخاب کنید</option>
                            <option value="خرید سرور">خرید سرور</option>
                            <option value="خرید حجم">خرید حجم</option>
                            <option value="تمدید سرور">تمدید سرور</option>
                            <option value="سایر">سایر</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="amount" class="form-label">مبلغ (تومان) <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="amount" name="amount" required>
                    </div>
                    <div class="mb-3">
                        <label for="transaction_date" class="form-label">تاریخ تراکنش <span class="text-danger">*</span></label>
                        <input type="date" class="form-control" id="transaction_date" name="transaction_date" value="<?= date('Y-m-d') ?>" required>
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">توضیحات</label>
                        <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
                    <button type="submit" class="btn btn-primary">ثبت هزینه</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
$data_tables_script = '
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script>
$(document).ready(function() {
    [\"#transactions-table\", \"#expenses-table\"].forEach(tableId => {
        $(tableId).DataTable({
            "order": [[ 0, "desc" ]],
            "language": {
                "url": "//cdn.datatables.net/plug-ins/1.13.6/i18n/fa.json"
            }
        });
    });
});
</script>';
require_once '../includes/footer.php';
?>
