<?php
require_once '../app/Models/Order.php';
require_once '../app/Models/Customer.php';
require_once '../app/Models/Product.php';
require_once '../app/Models/User.php';
class OrderController {
    private $order; private $customer; private $product; private $userModel;
    public function __construct(){ $this->auth(); $this->order=new Order(); $this->customer=new Customer(); $this->product=new Product(); $this->userModel=new User(); }
    private function auth(){ if(!isset($_SESSION['user_id'])){ header('Location:/samanta_crm/login'); exit; } }
    
    public function getLatest() {
        header('Content-Type: application/json');
        $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 5;
        $orders = $this->order->getLatest($limit);
        echo json_encode(['success' => true, 'orders' => $orders]);
        exit;
    }
    
    public function index(){
        $f=[
            'date_from'=>$_GET['date_from']??'',
            'date_to'=>$_GET['date_to']??'',
            'customer_id'=>$_GET['customer_id']??'',
            'status'=>$_GET['status']??'',
            'order_type'=>$_GET['order_type']??'',
            'verified'=>$_GET['verified']??''
        ];
        $orders=$this->order->filter($f);
        // Export
        if(isset($_GET['export']) && in_array($_GET['export'],['csv','excel'])){
            $this->export($orders,$_GET['export']); return;
        }
        $customers=$this->customer->all();
    $orderTypes=$this->order->getDistinctOrderTypes();
    $this->view('orders/index',[ 'orders'=>$orders,'filters'=>$f,'customers'=>$customers,'orderTypes'=>$orderTypes ]);
    }
    private function export($orders,$type){
        if($type==='csv'){
            header('Content-Type:text/csv'); header('Content-Disposition: attachment; filename="orders_export_'.date('Ymd_His').'.csv"');
            $out=fopen('php://output','w'); fputcsv($out,['ID','Order Date','Delivery Date','Type','Customer','Assigned','Status','Items','Verified']);
            foreach($orders as $o){ $cnt=$this->countItems($o['id']); fputcsv($out,[$o['id'],$o['order_date'],$o['delivery_date'],$o['order_type'],$o['customer_name'],$o['assigned_user_name'],$o['status'],$cnt, $o['confirmed']?'Yes':'']); }
            fclose($out); return;
        }
        if($type==='excel'){
            header('Content-Type: application/vnd.ms-excel; charset=utf-8'); header('Content-Disposition: attachment; filename="orders_export_'.date('Ymd_His').'.xls"');
            echo '<table border="1"><tr><th>ID</th><th>Order Date</th><th>Delivery Date</th><th>Type</th><th>Customer</th><th>Assigned</th><th>Status</th><th>Items</th><th>Verified</th></tr>';
            foreach($orders as $o){ $cnt=$this->countItems($o['id']); echo '<tr><td>'.$o['id'].'</td><td>'.htmlspecialchars($o['order_date']).'</td><td>'.htmlspecialchars($o['delivery_date']).'</td><td>'.htmlspecialchars($o['order_type']).'</td><td>'.htmlspecialchars($o['customer_name']).'</td><td>'.htmlspecialchars($o['assigned_user_name']).'</td><td>'.htmlspecialchars($o['status']).'</td><td>'.$cnt.'</td><td>'.($o['confirmed']?'Yes':'').'</td></tr>'; }
            echo '</table>'; return;
        }
    }
    private function countItems($orderId){ $st=$GLOBALS['pdo']->query("SELECT COUNT(DISTINCT product_id) FROM order_items WHERE order_id=".(int)$orderId); return (int)$st->fetchColumn(); }
    public function create(){
        $customers = $this->customer->all();
        $userList = $this->userModel->getAll()['data'];
        $custUserMap = [];
        foreach($customers as $c){ $custUserMap[$c['id']] = array_map(function($u){ return ['id'=>$u['id'],'name'=>$u['name']]; }, $this->customer->users($c['id'])); }
        $this->view('orders/create',[ 'customers'=>$customers,'products'=>$this->product->search('','','all',500,0),'users'=>$userList,'customer_user_map'=>$custUserMap ]);
    }
    public function panel(){ // tablet optimized create
        $customers=$this->customer->all();
        $userList=$this->userModel->getAll()['data'];
        $custUserMap = [];
        foreach($customers as $c){ $custUserMap[$c['id']] = array_map(function($u){ return ['id'=>$u['id'],'name'=>$u['name']]; }, $this->customer->users($c['id'])); }
        $this->view('orders/panel',[ 'customers'=>$customers,'products'=>$this->product->search('','','all',1000,0),'users'=>$userList,'customer_user_map'=>$custUserMap ]);
    }
    public function store(){ if($_SERVER['REQUEST_METHOD']!=='POST'){ header('Location:/samanta_crm/orders'); exit; } $data=$this->collect(); $orderId=$this->order->create($data); if($orderId){ $items=$this->collectItems(); $this->order->replaceItems($orderId,$items); $_SESSION['success']='Order created'; } else { $_SESSION['error']='Create failed'; } header('Location:/samanta_crm/orders'); }
    public function edit($id){ $o=$this->order->find($id); if(!$o){ $_SESSION['error']='Not found'; header('Location:/samanta_crm/orders'); exit; } $items=$this->order->items($id); $customers=$this->customer->all(); $userList=$this->userModel->getAll()['data']; $custUserMap=[]; foreach($customers as $c){ $custUserMap[$c['id']] = array_map(function($u){ return ['id'=>$u['id'],'name'=>$u['name']]; }, $this->customer->users($c['id'])); } $this->view('orders/edit',[ 'order'=>$o,'items'=>$items,'customers'=>$customers,'products'=>$this->product->search('','','all',500,0),'users'=>$userList,'customer_user_map'=>$custUserMap ]); }
    public function show($id){ 
        $o=$this->order->find($id); 
        if(!$o){ $_SESSION['error']='Not found'; header('Location:/samanta_crm/orders'); exit; } 
        $items=$this->order->items($id); 
        
        // Handle export for individual order items
        if(isset($_GET['export']) && in_array($_GET['export'],['csv','excel'])){
            $this->exportOrderItems($o, $items, $_GET['export']); return;
        }
        
        $this->view('orders/show',[ 'order'=>$o,'items'=>$items ]); 
    }
    public function update($id){
        if($_SERVER['REQUEST_METHOD']!=='POST'){ header('Location:/samanta_crm/orders'); exit; }
        $data=$this->collect();
        if($this->order->update($id,$data)){
            $items=$this->collectItems();
            $this->order->replaceItems($id,$items);
            if(isset($_POST['confirm_flag']) && $_POST['confirm_flag']=='1'){
                $this->order->confirm($id,$_SESSION['user_id']??null);
            } else {
                // Allow un-verifying if previously verified and user unchecks
                $this->order->unconfirm($id);
            }
            $_SESSION['success']='Updated';
        } else { $_SESSION['error']='Update failed'; }
        header('Location:/samanta_crm/orders');
    }
    public function delete($id){ if($_SERVER['REQUEST_METHOD']!=='POST'){ header('Location:/samanta_crm/orders'); exit; } $this->order->delete($id); $_SESSION['success']='Deleted'; header('Location:/samanta_crm/orders'); }
    private function collect(){
        $orderDatePart = $_POST['order_date'] ?: date('Y-m-d');
        if(strtotime($orderDatePart) < strtotime(date('Y-m-d'))) { $orderDatePart = date('Y-m-d'); }
        $orderTime = $_POST['order_time'] ?? date('H:i');
        // basic HH:MM validation
        if(!preg_match('/^\d{2}:\d{2}$/',$orderTime)) $orderTime = date('H:i');
        $orderDate = $orderDatePart.' '. $orderTime.':00';
        $deliveryDate = $_POST['delivery_date'] ?? null;
        if($deliveryDate){
            // Enforce delivery >= order date
            if(strtotime($deliveryDate) < strtotime($orderDate)) $deliveryDate = $orderDate;
        }
        return [
            'customer_id'=>$_POST['customer_id'],
            'order_date'=>$orderDate,
            'delivery_date'=>$deliveryDate,
            'order_type'=>$_POST['order_type']??'daily',
            'status'=>$_POST['status']??'pending',
            'notes'=>$_POST['notes']??null,
            'signature'=>$_POST['signature']??null,
            'assigned_user_id'=>$_POST['assigned_user_id']?:null,
            'created_by'=>$_SESSION['user_id']??null
        ]; }
    private function collectItems(){ $items=[]; if(isset($_POST['item_product_id'])){ foreach($_POST['item_product_id'] as $i=>$pid){ if(!$pid) continue; $qty=str_replace(',','.', $_POST['item_qty'][$i]??'1'); if(!is_numeric($qty)) $qty=1; $price=isset($_POST['item_price'][$i]) && $_POST['item_price'][$i]!==''? str_replace(',','.', $_POST['item_price'][$i]): null; $pName=$_POST['item_name_snapshot'][$i] ?? ($_POST['item_name'][$i]??''); $pCode=$_POST['item_code_snapshot'][$i] ?? ''; $items[]=['product_id'=>$pid,'quantity'=>$qty,'unit_price'=>$price,'product_name_snapshot'=>$pName,'product_code_snapshot'=>$pCode]; } } return $items; }
    private function exportOrderItems($order, $items, $type){
        $filename = "order_{$order['id']}_items_" . date('Ymd_His');
        if($type==='csv'){
            header('Content-Type:text/csv'); 
            header("Content-Disposition: attachment; filename=\"{$filename}.csv\"");
            $out=fopen('php://output','w'); 
            fputcsv($out,['Order ID','Code','Name','Qty','Units']);
            foreach($items as $it){ 
                $qty = (float)$it['quantity'];
                $units = ($it['price_unit'] ?? '') ?: ($it['production_unit'] ?? '');
                fputcsv($out,[
                    $order['id'],
                    ($it['product_code_snapshot']??'') ?: ($it['code']??''),
                    ($it['product_name_snapshot']??'') ?: ($it['name']??''),
                    number_format($qty,1),
                    $units
                ]); 
            }
            fclose($out); return;
        }
        if($type==='excel'){
            header('Content-Type: application/vnd.ms-excel; charset=utf-8'); 
            header("Content-Disposition: attachment; filename=\"{$filename}.xls\"");
            echo '<table border="1">';
            echo '<tr><th>Order ID</th><th>Code</th><th>Name</th><th>Qty</th><th>Units</th></tr>';
            foreach($items as $it){ 
                $qty = (float)$it['quantity'];
                $units = ($it['price_unit'] ?? '') ?: ($it['production_unit'] ?? '');
                echo '<tr>';
                echo '<td>'.$order['id'].'</td>';
                echo '<td>'.htmlspecialchars(($it['product_code_snapshot']??'') ?: ($it['code']??'')).'</td>';
                echo '<td>'.htmlspecialchars(($it['product_name_snapshot']??'') ?: ($it['name']??'')).'</td>';
                echo '<td>'.number_format($qty,1).'</td>';
                echo '<td>'.htmlspecialchars($units).'</td>';
                echo '</tr>';
            }
            echo '</table>'; return;
        }
    }
    private function view($v,$d=[]){ extract($d); require_once "../app/Views/$v.php"; }
}
