<?php
session_start();
if (!isset($_SESSION['user_id'])) { http_response_code(403); exit(json_encode(['success'=>false,'message'=>(function_exists('crmTranslateMessage') ? crmTranslateMessage('Unauthorized') : 'Unauthorized')])); }
require_once '../connect.php';
$account_id=(int)$_SESSION['account_id'];
$user_id=(int)$_SESSION['user_id'];
$raw=file_get_contents('php://input');
$json=$raw?json_decode($raw,true):null; if (is_array($json)) crmDecodeIdsInArray($json); crmDecodeIdsInArray($_POST);
$action=$_POST['action'] ?? ($json['action'] ?? '');

switch($action){
  case 'save':
    $id=crmId($_POST['id'] ?? 0);
    requirePermission($conn,'quotations',$id?'edit':'add');
    $customer_id=(int)($_POST['customer_id'] ?? 0);
    $itemsInput = $_POST['items'] ?? [];
    if (isset($_POST['items_json']) && $_POST['items_json']) { $itemsInput = json_decode($_POST['items_json'], true) ?: []; }
    $legacyItem=(int)($_POST['item_id'] ?? 0);
    if (!$itemsInput && $legacyItem) $itemsInput = [['item_id'=>$legacyItem,'quantity'=>($_POST['quantity']??1),'unit_price'=>($_POST['unit_price']??0)]];
    $cleanItems=[]; foreach($itemsInput as $row){ $iid=crmId($row['item_id']??0); if(!$iid) continue; $qty=max(1,(int)($row['quantity']??1)); $price=(float)($row['unit_price']??0); $cleanItems[]=['item_id'=>$iid,'quantity'=>$qty,'unit_price'=>$price]; }
    $item_id = $cleanItems[0]['item_id'] ?? 0;
    $quantity = $cleanItems[0]['quantity'] ?? 1;
    $unit_price = $cleanItems[0]['unit_price'] ?? 0;
    $discount=max(0,(float)($_POST['discount'] ?? 0));
    $tva_percent=max(0,(float)($_POST['tva_percent'] ?? 0));
    $status=sanitize($conn,$_POST['status'] ?? 'draft');
    $valid_until=sanitize($conn,$_POST['valid_until'] ?? '');
    $notes=sanitize($conn,$_POST['notes'] ?? '');
    $customer_details=sanitize($conn,$_POST['customer_details'] ?? '');
    $reminder_date=sanitize($conn,$_POST['reminder_date'] ?? '');
    $reminder_time=sanitize($conn,$_POST['reminder_time'] ?? '');
    $reminder_note=sanitize($conn,$_POST['reminder_note'] ?? '');
    if($id && (!$cleanItems || !$item_id)){
      $oldItems=[];
      if (tableExists($conn,'quotation_items')) { $oq=$conn->query("SELECT item_id,quantity,unit_price FROM quotation_items WHERE quotation_id=$id ORDER BY id"); while($oq && $or=$oq->fetch_assoc()) $oldItems[]=$or; }
      if (!$oldItems) { $orow=$conn->query("SELECT item_id,quantity,unit_price FROM quotations WHERE id=$id AND account_id=$account_id LIMIT 1"); if($orow && $orow->num_rows) $oldItems[]=$orow->fetch_assoc(); }
      $cleanItems=[]; foreach($oldItems as $row){ $iid=(int)($row['item_id']??0); if(!$iid) continue; $qty=max(1,(int)($row['quantity']??1)); $price=(float)($row['unit_price']??0); $cleanItems[]=['item_id'=>$iid,'quantity'=>$qty,'unit_price'=>$price]; }
      $item_id = $cleanItems[0]['item_id'] ?? 0; $quantity = $cleanItems[0]['quantity'] ?? 1; $unit_price = $cleanItems[0]['unit_price'] ?? 0;
    }
    if(!$customer_id || !$item_id || !$cleanItems) jsonResponse(false,'Customer and at least one item are required');
    $sub=0; foreach($cleanItems as $ci){ $sub += $ci['quantity']*$ci['unit_price']; } $after=max(0,$sub-$discount); $tva_value=$after*$tva_percent/100; $total=$after+$tva_value;
    $valid_sql=$valid_until?"'$valid_until'":"NULL";
    $remDateSql=$reminder_date?"'$reminder_date'":"NULL"; $remTimeSql=$reminder_time?"'$reminder_time'":"NULL";
    if($id){
      $conn->query("UPDATE quotations SET customer_id=$customer_id,item_id=$item_id,quantity=$quantity,unit_price=$unit_price,discount=$discount,tva_percent=$tva_percent,tva_value=$tva_value,total=$total,status='$status',valid_until=$valid_sql,notes='$notes',customer_details='$customer_details',reminder_date=$remDateSql,reminder_time=$remTimeSql,reminder_note='$reminder_note',updated_by=$user_id,date_updated=NOW() WHERE id=$id AND account_id=$account_id");
      if($reminder_date){ $conn->query("INSERT INTO reminder (`date`,`time`,`comment`,`customer_id`,`quotation_id`,`user_id`,`status`,`account_id`) VALUES ('$reminder_date', $remTimeSql, '$reminder_note', $customer_id, $id, $user_id, 'pending', $account_id)"); }
      if (tableExists($conn,'quotation_items')) { $conn->query("DELETE FROM quotation_items WHERE quotation_id=$id"); foreach($cleanItems as $ci){ $iid=(int)$ci['item_id']; $qty=(int)$ci['quantity']; $up=(float)$ci['unit_price']; $line=$qty*$up; $conn->query("INSERT INTO quotation_items (quotation_id,item_id,quantity,unit_price,line_total) VALUES ($id,$iid,$qty,$up,$line)"); } }
      jsonResponse(true,'Quotation updated',['id'=>crmEncodeId($id)]);
    } else {
      $conn->query("INSERT INTO quotations (account_id,customer_id,item_id,quantity,unit_price,discount,tva_percent,tva_value,total,status,valid_until,notes,customer_details,reminder_date,reminder_time,reminder_note,created_by) VALUES ($account_id,$customer_id,$item_id,$quantity,$unit_price,$discount,$tva_percent,$tva_value,$total,'$status',$valid_sql,'$notes','$customer_details',$remDateSql,$remTimeSql,'$reminder_note',$user_id)");
      $newId=(int)$conn->insert_id; if($reminder_date){ $conn->query("INSERT INTO reminder (`date`,`time`,`comment`,`customer_id`,`quotation_id`,`user_id`,`status`,`account_id`) VALUES ('$reminder_date', $remTimeSql, '$reminder_note', $customer_id, $newId, $user_id, 'pending', $account_id)"); }
      if (tableExists($conn,'quotation_items')) { foreach($cleanItems as $ci){ $iid=(int)$ci['item_id']; $qty=(int)$ci['quantity']; $up=(float)$ci['unit_price']; $line=$qty*$up; $conn->query("INSERT INTO quotation_items (quotation_id,item_id,quantity,unit_price,line_total) VALUES ($newId,$iid,$qty,$up,$line)"); } }
      jsonResponse(true,'Quotation added',['id'=>crmEncodeId($newId)]);
    }
  case 'get':
    requirePermission($conn,'quotations','open');
    $id=(int)($json['id'] ?? $_POST['id'] ?? 0);
    $r=$conn->query("SELECT q.*, c.customer_name, c.business_name, c.phone, c.email, c.address, i.name item_name, a.client_name account_client_name, a.business_name account_business_name, a.phone account_phone, a.email account_email, a.currency account_currency, a.logo account_logo FROM quotations q LEFT JOIN customers c ON c.id=q.customer_id LEFT JOIN items i ON i.id=q.item_id LEFT JOIN accounts a ON a.id=q.account_id WHERE q.id=$id AND q.account_id=$account_id LIMIT 1");
    if(!$r || !$r->num_rows) jsonResponse(false,'Quotation not found');
    $data=$r->fetch_assoc(); $data['id_eid']=crmEncodeId((int)$data['id']); $data['customer_id_eid']=crmEncodeId((int)$data['customer_id']); $items=[]; if(tableExists($conn,'quotation_items')){ $iq=$conn->query("SELECT qi.*, i.name item_name, i.currency FROM quotation_items qi LEFT JOIN items i ON i.id=qi.item_id WHERE qi.quotation_id=$id ORDER BY qi.id"); while($iq && $ir=$iq->fetch_assoc()){ $ir['item_id_eid']=crmEncodeId((int)$ir['item_id']); $items[]=$ir; } } jsonResponse(true,'',['data'=>$data,'items'=>$items]);
  case 'delete':
    requirePermission($conn,'quotations','delete');
    $id=(int)($json['id'] ?? $_POST['id'] ?? 0);
    $conn->query("DELETE FROM quotations WHERE id=$id AND account_id=$account_id");
    jsonResponse(true,'Deleted');
  default:
    jsonResponse(false,'Invalid action');
}
