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

class Initialize_cash_account extends MY_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load_global();
    }
    
    /**
     * Initialize Cash Account for all stores
     * This can be called during system setup or manually
     */
    public function init_all_stores() {
        $this->load->helper('cash_account_helper');
        
        // Get all stores
        $stores = $this->db->get('db_store')->result();
        
        $results = array();
        foreach ($stores as $store) {
            $cash_account_id = create_default_cash_account($store->id);
            $results[] = array(
                'store_id' => $store->id,
                'store_name' => $store->store_name,
                'cash_account_id' => $cash_account_id,
                'status' => $cash_account_id ? 'created' : 'failed'
            );
        }
        
        echo json_encode(array(
            'success' => true,
            'message' => 'Cash Accounts initialized for all stores',
            'results' => $results
        ));
    }
    
    /**
     * Initialize Cash Account for current store
     */
    public function init_current_store() {
        $this->load->helper('cash_account_helper');
        
        $store_id = get_current_store_id();
        $cash_account_id = create_default_cash_account($store_id);
        
        if ($cash_account_id) {
            echo json_encode(array(
                'success' => true,
                'message' => 'Cash Account created successfully',
                'cash_account_id' => $cash_account_id
            ));
        } else {
            echo json_encode(array(
                'success' => false,
                'message' => 'Failed to create Cash Account'
            ));
        }
    }
    
    /**
     * Check if Cash Account exists for current store
     */
    public function check_cash_account() {
        $this->load->helper('cash_account_helper');
        
        $store_id = get_current_store_id();
        $cash_account_id = get_cash_account_id($store_id);
        
        echo json_encode(array(
            'exists' => $cash_account_id ? true : false,
            'cash_account_id' => $cash_account_id
        ));
    }
}
