<?php
namespace App\Modules\Finance\Controllers;

class FinanceController extends \Core\Controller {
    


    public function index() {
        $model = $this->model('Finance/Models/FinanceModel');

        // Which tab is active?
        $activeTab = isset($_GET['tab']) ? sanitize_input($_GET['tab']) : 'income';

        // Pagination parameters
        $pageInc = isset($_GET['page_inc']) ? (int)$_GET['page_inc'] : 1;
        $pageExp = isset($_GET['page_exp']) ? (int)$_GET['page_exp'] : 1;
        $perPage = 5; // Reduced as per user feedback
        
        // Fetch aggregates
        $incomeSummary = $model->getIncomeSummary($this->userId);
        $totalExpense = $model->getExpenseSummary($this->userId);

        // Fetch tables data (Paginated)
        $incomesPaginated = $model->getIncomes($this->userId, $pageInc, $perPage);
        $expensesPaginated = $model->getExpenses($this->userId, $pageExp, $perPage);

        $goals = $model->getSavingGoals($this->userId);
        $installments = $model->getInstallments($this->userId);
        $debts = $model->getDebts($this->userId);
        $investments = $model->getInvestments($this->userId);

        // Fetch Wallet & Account Intelligence
        $walletBalances = $model->getWalletBalances($this->userId);
        $accountAnalysis = $model->getMonthlyAccountAnalysis($this->userId);

        // Fetch categories dynamically
        $incomeCategories = $model->getCategories($this->userId, 'income');
        $expenseCategories = $model->getCategories($this->userId, 'expense');

        require_once __DIR__ . '/../../../../core/Services/FinanceAnalysisService.php';
        $finService = new \Core\Services\FinanceAnalysisService();
        $timeframe = isset($_GET['timeframe']) && $_GET['timeframe'] === 'current_month' ? 'current_month' : 30;
        $financeAnalysis = $finService->analyze($this->userId, $timeframe);

        $this->view('Finance/Views/dashboard', [
            'title' => 'الإدارة المالية الشاملة',
            'activeTab' => $activeTab,
            'timeframe' => $timeframe,
            'incomeSummary' => $incomeSummary,
            'totalExpense' => $totalExpense,
            'financeAnalysis' => $financeAnalysis,
            'incomes' => $incomesPaginated['data'],
            'incomePagination' => $incomesPaginated['pagination'],
            'expenses' => $expensesPaginated['data'],
            'expensePagination' => $expensesPaginated['pagination'],
            'goals' => $goals,
            'installments' => $installments,
            'debts' => $debts,
            'investments' => $investments,
            'incomeCategories' => $incomeCategories,
            'expenseCategories' => $expenseCategories,
            'walletBalances' => $walletBalances,
            'accountAnalysis' => $accountAnalysis
        ]);
    }

    public function apiPaginateList() {
        $type = isset($_GET['type']) ? $_GET['type'] : '';
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        $perPage = 5;
        
        $model = $this->model('Finance/Models/FinanceModel');
        if ($type === 'expense') {
            $paginated = $model->getExpenses($this->userId, $page, $perPage);
            $expenses = $paginated['data'];
            $expensePagination = $paginated['pagination'];
            $expenseCategories = $model->getCategories($this->userId, 'expense');
            $incomeCategories = $model->getCategories($this->userId, 'income');
            include __DIR__ . '/../Views/partials/_expense_table.php';
        } elseif ($type === 'income') {
            $paginated = $model->getIncomes($this->userId, $page, $perPage);
            $incomes = $paginated['data'];
            $incomePagination = $paginated['pagination'];
            include __DIR__ . '/../Views/partials/_income_table.php';
        }
    }

    // --- Dynamic Categories ---
    public function apiManageCategory() {
        header('Content-Type: application/json');
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode(['success' => false]);
            return;
        }
        if (!isset($_POST['csrf_token']) || !isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
            echo json_encode(['success' => false, 'message' => 'خطأ أمني: يرجى تحديث الصفحة والمحاولة مجدداً.']);
            return;
        }
        
        $model = $this->model('Finance/Models/FinanceModel');
        $action = $_POST['action'] ?? '';
        
        if ($action === 'add') {
            $budget = get_secure_post('budget');
            if ($budget === '' || $budget === null) $budget = null;
            $type = get_secure_post('type');
            $linkedFund = ($type === 'expense') ? (get_secure_post('linked_fund') ?: 'personal') : 'personal';
            $color = get_secure_post('color') ?: '#6366f1';
            // Validate color is a hex code
            if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $color)) $color = '#6366f1';
            $model->addCategory($this->userId, $type, get_secure_post('name'), $budget, $linkedFund, $color);
        } elseif ($action === 'delete') {
            $model->deleteCategory(get_secure_post('id'), $this->userId);
        }
        
        $inc = $model->getCategories($this->userId, 'income');
        $exp = $model->getCategories($this->userId, 'expense');
        
        echo json_encode(['success' => true, 'income' => $inc, 'expense' => $exp]);
    }

    // --- Form Handlers ---
    public function storeIncome() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $model = $this->model('Finance/Models/FinanceModel');
            $amount = (float)get_secure_post('amount');
            $date = get_secure_post('date_received');
            $source = trim(get_secure_post('source'));
            
            if ($amount <= 0 || !strtotime($date) || empty($source)) {
                set_flash_message('finance', 'بيانات الدخل غير صالحة. يرجى التأكد من المبلغ والتاريخ والمصدر.', 'danger');
                redirect('/finance?tab=income');
            }

            $model->addIncome(
                $this->userId,
                $source,
                $amount,
                $date
            );
            
            set_flash_message('finance', 'تم إضافة الدخل بنجاح!', 'success');
            redirect('/finance?tab=income');
        }
    }

    public function storeExpense() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $model    = $this->model('Finance/Models/FinanceModel');
            $amount   = (float)get_secure_post('amount');
            $date     = get_secure_post('expense_date');
            $category = trim(get_secure_post('category'));
            $itemName = trim(get_secure_post('item_name')); // البند - free-text description
            
            if ($amount <= 0 || !strtotime($date) || empty($category) || empty($itemName)) {
                set_flash_message('finance', 'بيانات المصروف غير صالحة. يرجى مراجعة كافة الحقول.', 'danger');
                redirect('/finance?tab=income');
            }

            $model->addExpense(
                $this->userId,
                $category,
                $itemName,
                $amount,
                $date,
                get_secure_post('notes')
            );
            
            set_flash_message('finance', 'تم تسجيل المصروف!', 'success');
            redirect('/finance?tab=income');
        }
    }

    public function storeSavingGoal() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $model = $this->model('Finance/Models/FinanceModel');
            $model->addSavingGoal(
                $this->userId, 
                get_secure_post('title'), 
                get_secure_post('target_amount'),
                get_secure_post('expected_date')
            );
            set_flash_message('finance', 'تم بدء تحدي الادخار.', 'success');
            redirect('/finance?tab=savings');
        }
    }

    public function addSavingProgress() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $model = $this->model('Finance/Models/FinanceModel');
            $model->updateSavingGoalProgress(get_secure_post('goal_id'), $this->userId, get_secure_post('amount'));
            set_flash_message('finance', 'تم تحديث المدخرات بنجاح.', 'success');
            redirect('/finance?tab=savings');
        }
    }

    public function storeInstallment() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $model = $this->model('Finance/Models/FinanceModel');
            $model->addInstallment(
                $this->userId, 
                get_secure_post('name'), 
                get_secure_post('icon'), 
                get_secure_post('total_months'), 
                get_secure_post('monthly_amount'),
                get_secure_post('start_date')
            );
            set_flash_message('finance', 'تم تسجيل القسط كمنتج.', 'success');
            redirect('/finance?tab=debts');
        }
    }

    public function updateInstallmentPaidState() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $model = $this->model('Finance/Models/FinanceModel');
            $installmentId = get_secure_post('installment_id');
            $paidJson = get_secure_post('paid_json'); // String array '[1, 2]' built by UI JS

            $model->updateInstallmentPaidMonths($installmentId, $this->userId, $paidJson);
            set_flash_message('finance', 'تم تحديث سجل الدفع الخاص بالقسط!', 'success');
            redirect('/finance?tab=debts');
        }
    }

    public function storeDebt() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $model = $this->model('Finance/Models/FinanceModel');
            $model->addDebt($this->userId, get_secure_post('person_name'), get_secure_post('amount'), get_secure_post('type'), get_secure_post('due_date'));
            set_flash_message('finance', 'تم تسجيل الدين.', 'success');
            redirect('/finance?tab=debts');
        }
    }

    public function storeDebtPayment() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $model = $this->model('Finance/Models/FinanceModel');
            
            $amount = (float)get_secure_post('amount');
            if($amount <= 0) {
                set_flash_message('finance', 'مبلغ السداد يجب أن يكون أكبر من الصفر', 'danger');
                redirect('/finance?tab=debts');
            }

            $model->addDebtPartialPayment(
                $this->userId,
                get_secure_post('debt_id'),
                $amount,
                get_secure_post('payment_date'),
                get_secure_post('notes')
            );
            
            set_flash_message('finance', 'تم تسجيل السداد الجزئي.', 'success');
            redirect('/finance?tab=debts');
        }
    }

    public function toggleDebt($id) {
        $model = $this->model('Finance/Models/FinanceModel');
        $model->resolveDebt($id, $this->userId);
        set_flash_message('finance', 'تم تحديث حالة الدين لتغلق.', 'success');
        redirect('/finance?tab=debts');
    }

    public function storeInvestment() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $model = $this->model('Finance/Models/FinanceModel');
            $model->addInvestment(
                $this->userId, 
                get_secure_post('asset_name'), 
                get_secure_post('asset_type'), 
                get_secure_post('buy_price'),
                get_secure_post('quantity'),
                get_secure_post('buy_price') // Initial current_price == buy_price
            );
            set_flash_message('finance', 'تم تسجيل الأصل الاستثماري وتتبعه.', 'success');
            redirect('/finance?tab=investments');
        }
    }
    
    public function updateInvestment($id) {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $model = $this->model('Finance/Models/FinanceModel');
            $model->updateInvestmentData(
                $id, 
                $this->userId, 
                get_secure_post('current_value'), 
                get_secure_post('quantity'), 
                get_secure_post('buy_price')
            );
            set_flash_message('finance', 'تم تحديث بيانات الأصل الاستثماري.', 'success');
            redirect('/finance?tab=investments');
        }
    }

    // --- GENERIC CRUD ACTIONS ---
    private function getTabByTable($table) {
        $map = [
            'finance_incomes' => 'income',
            'finance_expenses' => 'income',
            'fin_categories' => 'income',
            'finance_saving_goals' => 'savings',
            'finance_installments' => 'debts',
            'finance_debts' => 'debts',
            'finance_investments' => 'investments'
        ];
        return $map[$table] ?? 'income';
    }

    public function delete($table, $id) {
        $model = $this->model('Finance/Models/FinanceModel');
        if ($model->deleteItem($table, $id, $this->userId)) {
            set_flash_message('finance', 'تم نقل السجل لسلة المحذوفات بنجاح.', 'success');
        } else {
            set_flash_message('finance', 'حدث خطأ أثناء المحاولة.', 'danger');
        }
        redirect('/finance?tab=' . $this->getTabByTable($table));
    }

    public function edit($table, $id) {
        $model = $this->model('Finance/Models/FinanceModel');
        $item = $model->getItem($table, $id, $this->userId);
        
        if (!$item) {
            set_flash_message('finance', 'السجل غير موجود أو تم حذفه.', 'error');
            redirect('/finance?tab=' . $this->getTabByTable($table));
        }

        $data = [
            'title' => 'تعديل السجل المالي',
            'table' => $table,
            'item' => $item,
            'returnTab' => $this->getTabByTable($table)
        ];

        if ($table === 'finance_expenses') {
            $data['categories'] = $model->getCategories($this->userId);
        }

        $this->view('Finance/Views/edit', $data);
    }

    public function update() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $model = $this->model('Finance/Models/FinanceModel');
            
            $table = get_secure_post('table_name');
            $id = get_secure_post('item_id');
            
            $data = [];
            foreach ($_POST as $key => $val) {
                if (!in_array($key, ['csrf_token', 'table_name', 'item_id', '_pjax', '_'])) {
                    $data[$key] = sanitize_input($val);
                }
            }
            
            if ($model->updateItem($table, $id, $this->userId, $data)) {
                set_flash_message('finance', 'تم تعديل السجل وتحديثه فورياً.', 'success');
            } else {
                set_flash_message('finance', 'لم يتم العثور على تغييرات أو السجل غير موجود.', 'warning');
            }
            
            redirect('/finance?tab=' . $this->getTabByTable($table));
        }
    }
}

