<?php
require_once '../app/Models/Customer.php';
require_once '../app/Models/Category.php';
require_once '../app/Models/Product.php';
require_once '../app/Models/User.php';
class CustomerController {
    private $model; private $category; private $product; private $userModel;
    public function __construct(){ $this->auth(); $this->model=new Customer(); $this->category=new Category(); $this->product=new Product(); $this->userModel=new User(); }
    private function auth(){ if(!isset($_SESSION['user_id'])){ redirect('login'); exit; } }
    
    public function index(){ 
        // Check if AJAX request
        if (isset($_GET['ajax']) && $_GET['ajax'] == '1') {
            header('Content-Type: application/json');
            
            $filters = [
                'type' => $_GET['type'] ?? 'inhouse',
                'search' => $_GET['search'] ?? '',
                'page' => (int)($_GET['page'] ?? 1),
                'per_page' => (int)($_GET['per_page'] ?? 25)
            ];
            
            $customers = $this->model->filter($filters);
            $totalCount = $this->model->getFilteredCount($filters);
            
            $totalPages = ceil($totalCount / $filters['per_page']);
            
            echo json_encode([
                'customers' => $customers,
                'pagination' => [
                    'current_page' => $filters['page'],
                    'per_page' => $filters['per_page'],
                    'total_count' => $totalCount,
                    'total_pages' => $totalPages,
                    'has_prev' => $filters['page'] > 1,
                    'has_next' => $filters['page'] < $totalPages
                ]
            ]);
            exit;
        }
        
        // Regular page load
        $this->view('customers/index', []); 
    }
    public function create(){ $this->view('customers/create',[ 'categories'=>$this->category->all(),'products'=>$this->product->search('','','all',500,0),'users'=>$this->userModel->getAll()['data'] ]); }
    public function store(){ if($_SERVER['REQUEST_METHOD']!=='POST'){ redirect('customers'); exit; } $data=$this->collect(); if($data['name']===''){ $_SESSION['error']='Name required'; redirect('customers/create'); exit; } if($this->model->create($data)){ $id=$GLOBALS['pdo']->lastInsertId(); $this->saveRelations($id); $_SESSION['success']='Customer created'; } else { $_SESSION['error']='Create failed'; } redirect('customers'); }
    public function edit($id){ $c=$this->model->find($id); if(!$c){ $_SESSION['error']='Not found'; redirect('customers'); exit; } $counts=$this->model->relationCounts($id); $this->view('customers/edit',[ 'customer'=>$c,'categories'=>$this->category->all(),'products'=>$this->product->search('','','all',500,0),'users'=>$this->userModel->getAll()['data'],'sel_categories'=>$this->model->categories($id),'sel_blocked'=>$this->model->blockedProducts($id),'sel_additional'=>$this->model->additionalProducts($id),'sel_users'=>$this->model->users($id),'relation_counts'=>$counts ]); }
    public function update($id){ if($_SERVER['REQUEST_METHOD']!=='POST'){ redirect('customers'); exit; } $data=$this->collect(); if($data['name']===''){ $_SESSION['error']='Name required'; redirect('customers/' . $id.'/edit'); exit; } if($this->model->update($id,$data)){ $this->saveRelations($id); $_SESSION['success']='Updated'; } else { $_SESSION['error']='Update failed'; } redirect('customers'); }
    public function delete($id){ if($_SERVER['REQUEST_METHOD']!=='POST'){ redirect('customers'); exit; } $this->model->delete($id); $_SESSION['success']='Deleted'; redirect('customers'); }
    private function collect(){ return [ 'name'=>trim($_POST['name']??''), 'email'=>trim($_POST['email']??''), 'phone'=>trim($_POST['phone']??''), 'address'=>trim($_POST['address']??''), 'notes'=>trim($_POST['notes']??''), 'status'=>$_POST['status']??'active', 'type'=>$_POST['type']??'customer' ]; }
    private function saveRelations($id){ $cats=$_POST['category_access']??[]; $blocked=$_POST['blocked_products']??[]; $additional=$_POST['additional_products']??[]; $users=$_POST['assigned_users']??[]; $this->model->syncCategories($id,$cats); $this->model->syncBlockedProducts($id,$blocked); $this->model->syncAdditionalProducts($id,$additional); $this->model->syncUsers($id,$users); }
    private function view($v,$d=[]){ extract($d); require_once "../app/Views/$v.php"; }
}


