<?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):[];
$action=$_POST['action'] ?? ($json['action'] ?? '');

switch($action){
  case 'list_questions':
    $item_id=(int)($json['item_id'] ?? $_POST['item_id'] ?? 0);
    $q=$conn->query("SELECT * FROM item_questions WHERE account_id=$account_id AND item_id=$item_id AND status=1 ORDER BY sort_order,id");
    $rows=[]; while($q && $r=$q->fetch_assoc()) $rows[]=$r;
    jsonResponse(true,'',['questions'=>$rows]);
  case 'save_question':
    requirePermission($conn,'items','edit');
    $id=(int)($_POST['id'] ?? ($json['id'] ?? 0));
    $item_id=(int)($_POST['item_id'] ?? ($json['item_id'] ?? 0));
    $question=sanitize($conn,$_POST['question'] ?? ($json['question'] ?? ''));
    $input_type=sanitize($conn,$_POST['input_type'] ?? ($json['input_type'] ?? 'text'));
    $options=sanitize($conn,$_POST['options_json'] ?? ($json['options_json'] ?? ''));
    $required=(int)($_POST['is_required'] ?? ($json['is_required'] ?? 0));
    $sort=(int)($_POST['sort_order'] ?? ($json['sort_order'] ?? 0));
    if(!$item_id || !$question) jsonResponse(false,'Item and question required');
    if($id){
      $conn->query("UPDATE item_questions SET question='$question', input_type='$input_type', options_json='$options', is_required=$required, sort_order=$sort WHERE id=$id AND account_id=$account_id");
      jsonResponse(true,'Question updated');
    } else {
      $conn->query("INSERT INTO item_questions (account_id,item_id,question,input_type,options_json,is_required,sort_order) VALUES ($account_id,$item_id,'$question','$input_type','$options',$required,$sort)");
      jsonResponse(true,'Question added',['id'=>$conn->insert_id]);
    }
  case 'delete_question':
    requirePermission($conn,'items','edit');
    $id=(int)($json['id'] ?? $_POST['id'] ?? 0);
    $conn->query("UPDATE item_questions SET status=0 WHERE id=$id AND account_id=$account_id");
    jsonResponse(true,'Question removed');
  case 'save_answers':
    requirePermission($conn,'leads','take_action');
    $lead_id=(int)($_POST['lead_id'] ?? ($json['lead_id'] ?? 0));
    $answers=$_POST['answers'] ?? ($json['answers'] ?? []);
    $lead=$conn->query("SELECT customer_id,item_id FROM leads WHERE id=$lead_id AND account_id=$account_id LIMIT 1");
    if(!$lead || !$lead->num_rows) jsonResponse(false,'Lead not found');
    $l=$lead->fetch_assoc(); $customer_id=(int)$l['customer_id']; $item_id=(int)$l['item_id'];
    foreach($answers as $qid=>$answer){
      $qid=(int)$qid; $answer=sanitize($conn,is_array($answer)?implode(',',$answer):$answer);
      $conn->query("INSERT INTO lead_question_answers (account_id,lead_id,customer_id,item_id,question_id,answer,answered_by) VALUES ($account_id,$lead_id,$customer_id,$item_id,$qid,'$answer',$user_id) ON DUPLICATE KEY UPDATE answer='$answer', answered_by=$user_id, date_updated=NOW()");
    }
    jsonResponse(true,'Answers saved');
  default: jsonResponse(false,'Invalid action');
}
