<?php
session_start();
if (!isset($_SESSION['user_id'])) { http_response_code(403); exit(json_encode(['success'=>false,'message'=>'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;
$action=$_POST['action'] ?? ($json['action'] ?? '');

switch($action){
  case 'save':
    $id=(int)($_POST['id'] ?? 0);
    requirePermission($conn,'quotations',$id?'edit':'add');
    $customer_id=(int)($_POST['customer_id'] ?? 0);
    $item_id=(int)($_POST['item_id'] ?? 0);
    $quantity=max(1,(int)($_POST['quantity'] ?? 1));
    $unit_price=(float)($_POST['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(!$customer_id || !$item_id) jsonResponse(false,'Customer and item are required');
    $sub=$quantity*$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)"); }
      jsonResponse(true,'Quotation updated',['id'=>$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)"); }
      jsonResponse(true,'Quotation added',['id'=>$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');
    jsonResponse(true,'',['data'=>$r->fetch_assoc()]);
  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');
}
