<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Dashboard extends Auth_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Account_model');
        $this->load->model('Transaction_model');
        $this->load->model('Card_model');
        $this->load->model('Crypto_wallet_model');
    }

    /**
     * Main dashboard
     */
    public function index() {
        // Get user accounts
        $accounts = $this->Account_model->get_by_user($this->user->id);
        
        // Calculate total balance
        $total_balance = 0;
        foreach ($accounts as $account) {
            $total_balance += floatval($account->available_balance ?? 0);
        }
        
        // Get primary account
        $primary_account = $this->Account_model->get_primary($this->user->id);
        
        // Get recent transactions
        $recent_transactions = $this->Transaction_model->get_by_user($this->user->id, [], 5);
        
        // Get user cards
        $cards = $this->Card_model->get_by_user($this->user->id);
        
        // Calculate income and expenses for current month
        $month_start = date('Y-m-01 00:00:00');
        $month_end = date('Y-m-t 23:59:59');
        
        $income = $this->_calculate_income($this->user->id, $month_start, $month_end);
        $expenses = $this->_calculate_expenses($this->user->id, $month_start, $month_end);
        
        // Get notifications
        $notifications = $this->Notification_model->get_by_user($this->user->id, 5);
        
        $this->data['title'] = 'Dashboard';
        $this->data['accounts'] = $accounts;
        $this->data['primary_account'] = $primary_account;
        $this->data['total_balance'] = $total_balance;
        $this->data['recent_transactions'] = $recent_transactions;
        $this->data['cards'] = $cards;
        $this->data['income'] = $income;
        $this->data['expenses'] = $expenses;
        $this->data['notifications'] = $notifications;
        
        $this->render('dashboard/index', $this->data);
    }

    /**
     * Calculate income for period
     */
    private function _calculate_income($user_id, $start_date, $end_date) {
        $this->db->select_sum('amount');
        $this->db->from('transactions');
        $this->db->join('accounts', 'accounts.id = transactions.destination_account_id');
        $this->db->where('accounts.user_id', $user_id);
        $this->db->where('transactions.status', 'completed');
        $this->db->where('transactions.created_at >=', $start_date);
        $this->db->where('transactions.created_at <=', $end_date);
        $result = $this->db->get()->row();
        return $result ? floatval($result->amount) : 0;
    }

    /**
     * Calculate expenses for period
     */
    private function _calculate_expenses($user_id, $start_date, $end_date) {
        $this->db->select_sum('amount');
        $this->db->from('transactions');
        $this->db->join('accounts', 'accounts.id = transactions.source_account_id');
        $this->db->where('accounts.user_id', $user_id);
        $this->db->where('transactions.status', 'completed');
        $this->db->where('transactions.created_at >=', $start_date);
        $this->db->where('transactions.created_at <=', $end_date);
        $result = $this->db->get()->row();
        return $result ? floatval($result->amount) : 0;
    }

    /**
     * Profile page
     */
    public function profile() {
        $this->data['title'] = 'Profile';
        $this->render('dashboard/profile', $this->data);
    }

    /**
     * Update profile
     */
    public function update_profile() {
        $this->form_validation->set_rules('first_name', 'First Name', 'required|min_length[2]');
        $this->form_validation->set_rules('last_name', 'Last Name', 'required|min_length[2]');
        $this->form_validation->set_rules('phone', 'Phone', 'required|min_length[10]');
        
        if (!$this->form_validation->run()) {
            if ($this->input->is_ajax_request()) {
                $this->error('Validation failed', validation_errors());
                return;
            }
            $this->session->set_flashdata('error', validation_errors());
            redirect('dashboard/profile');
            return;
        }
        
        // Check phone uniqueness
        $phone = $this->input->post('phone', TRUE);
        if ($this->User_model->phone_exists($phone, $this->user->id)) {
            $message = 'This phone number is already in use.';
            if ($this->input->is_ajax_request()) {
                $this->error($message);
                return;
            }
            $this->session->set_flashdata('error', $message);
            redirect('dashboard/profile');
            return;
        }
        
        $this->User_model->update($this->user->id, [
            'first_name' => $this->input->post('first_name', TRUE),
            'last_name' => $this->input->post('last_name', TRUE),
            'phone' => $phone,
            'date_of_birth' => $this->input->post('date_of_birth', TRUE),
            'gender' => $this->input->post('gender', TRUE),
            'address' => $this->input->post('address', TRUE),
            'city' => $this->input->post('city', TRUE),
            'state' => $this->input->post('state', TRUE)
        ]);
        
        $message = 'Profile updated successfully';
        if ($this->input->is_ajax_request()) {
            $this->success($message);
            return;
        }
        
        $this->session->set_flashdata('success', $message);
        redirect('dashboard/profile');
    }

    /**
     * Change password
     */
    public function change_password() {
        $this->form_validation->set_rules('current_password', 'Current Password', 'required');
        $this->form_validation->set_rules('new_password', 'New Password', 'required|min_length[8]');
        $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[new_password]');
        
        if (!$this->form_validation->run()) {
            if ($this->input->is_ajax_request()) {
                $this->error('Validation failed', validation_errors());
                return;
            }
            $this->session->set_flashdata('error', validation_errors());
            redirect('dashboard/profile');
            return;
        }
        
        // Verify current password
        if (!$this->User_model->verify_password($this->user->id, $this->input->post('current_password'))) {
            $message = 'Current password is incorrect';
            if ($this->input->is_ajax_request()) {
                $this->error($message);
                return;
            }
            $this->session->set_flashdata('error', $message);
            redirect('dashboard/profile');
            return;
        }
        
        $this->User_model->update($this->user->id, [
            'password' => $this->input->post('new_password')
        ]);
        
        // Send notification
        $this->Notification_model->send_security_notification($this->user->id, 'password_change');
        
        $message = 'Password changed successfully';
        if ($this->input->is_ajax_request()) {
            $this->success($message);
            return;
        }
        
        $this->session->set_flashdata('success', $message);
        redirect('dashboard/profile');
    }

    /**
     * Change transaction PIN
     */
    public function change_pin() {
        $this->form_validation->set_rules('current_pin', 'Current PIN', 'required|exact_length[4]');
        $this->form_validation->set_rules('new_pin', 'New PIN', 'required|exact_length[4]|numeric');
        $this->form_validation->set_rules('confirm_pin', 'Confirm PIN', 'required|matches[new_pin]');
        
        if (!$this->form_validation->run()) {
            if ($this->input->is_ajax_request()) {
                $this->error('Validation failed', validation_errors());
                return;
            }
            $this->session->set_flashdata('error', validation_errors());
            redirect('dashboard/profile');
            return;
        }
        
        // Verify current PIN
        if (!$this->User_model->verify_pin($this->user->id, $this->input->post('current_pin'))) {
            $message = 'Current PIN is incorrect';
            if ($this->input->is_ajax_request()) {
                $this->error($message);
                return;
            }
            $this->session->set_flashdata('error', $message);
            redirect('dashboard/profile');
            return;
        }
        
        $this->User_model->update($this->user->id, [
            'pin' => $this->input->post('new_pin')
        ]);
        
        // Send notification
        $this->Notification_model->send_security_notification($this->user->id, 'pin_change');
        
        $message = 'PIN changed successfully';
        if ($this->input->is_ajax_request()) {
            $this->success($message);
            return;
        }
        
        $this->session->set_flashdata('success', $message);
        redirect('dashboard/profile');
    }

    /**
     * Deposit / Receive page – bank info and crypto addresses with QR codes
     */
    public function deposit() {
        $crypto_wallets = $this->Crypto_wallet_model->get_wallets_for_deposit();
        $this->data['title'] = 'Deposit / Receive';
        $this->data['crypto_wallets'] = $crypto_wallets;
        $this->render('dashboard/deposit', $this->data);
    }

    /**
     * Settings page
     */
    public function settings() {
        $this->data['title'] = 'Settings';
        $this->render('dashboard/settings', $this->data);
    }

    /**
     * Notifications page
     */
    public function notifications() {
        $page = $this->input->get('page') ?: 1;
        $limit = 20;
        $offset = ($page - 1) * $limit;
        
        $notifications = $this->Notification_model->get_by_user($this->user->id, $limit, $offset);
        
        $this->data['title'] = 'Notifications';
        $this->data['notifications'] = $notifications;
        $this->data['page'] = $page;
        
        $this->render('dashboard/notifications', $this->data);
    }

    /**
     * View single notification
     */
    public function notification($id) {
        $notification = $this->Notification_model->get($id);
        
        if (!$notification || $notification->user_id != $this->user->id) {
            show_404();
            return;
        }
        
        // Mark as read
        $this->Notification_model->mark_as_read($id, $this->user->id);
        
        $this->data['title'] = 'Notification';
        $this->data['notification'] = $notification;
        
        $this->render('dashboard/notification_detail', $this->data);
    }

    /**
     * Mark all notifications as read
     */
    public function mark_all_read() {
        $this->Notification_model->mark_all_as_read($this->user->id);
        
        if ($this->input->is_ajax_request()) {
            $this->success('All notifications marked as read');
            return;
        }
        
        redirect('dashboard/notifications');
    }

    /**
     * Upload avatar
     */
    public function upload_avatar() {
        // Create upload directory if not exists
        $upload_path = FCPATH . 'uploads/avatars/';
        if (!is_dir($upload_path)) {
            mkdir($upload_path, 0755, true);
        }
        
        $config['upload_path'] = $upload_path;
        $config['allowed_types'] = 'gif|jpg|jpeg|png|webp';
        $config['max_size'] = 2048; // 2MB
        $config['file_name'] = 'avatar_' . $this->user->id . '_' . time();
        $config['overwrite'] = false;
        
        $this->load->library('upload', $config);
        
        if (!$this->upload->do_upload('avatar')) {
            $error = $this->upload->display_errors('', '');
            $this->session->set_flashdata('error', $error);
            redirect('dashboard/profile');
            return;
        }
        
        $upload_data = $this->upload->data();
        $filename = $upload_data['file_name'];
        
        // Delete old avatar if exists
        if (!empty($this->user->profile_photo)) {
            $old_file = $upload_path . $this->user->profile_photo;
            if (file_exists($old_file)) {
                unlink($old_file);
            }
        }
        
        // Update user profile photo
        $this->User_model->update($this->user->id, ['profile_photo' => $filename]);
        
        $this->session->set_flashdata('success', 'Profile photo updated successfully');
        redirect('dashboard/profile');
    }
}
