<?php
session_start();
require_once '../../config/database.php';
require_once 'csr_request_lock_helper.php';
require_once '../../includes/app_helpers.php';
header('Content-Type: application/json');
if (!isset($_SESSION['csr_id'])) { echo json_encode(['success'=>false,'message'=>'Unauthorized']); exit; }
try {
 $db=(new Database())->getConnection(); ensureOperationalTables($db); ensureUnifiedTicketWorkflow($db); ensureAddressAndCallQueueTables($db); ensureRequestLockTable($db);
 $csrId=(int)$_SESSION['csr_id']; $requestId=(int)($_POST['request_id']??0);
 if($requestId<=0){ echo json_encode(['success'=>false,'message'=>'Invalid request.']); exit; }
 requireCsrRequestAccessJson($db,$csrId,$requestId);
 $lock=getRequestLock($db,$requestId);
 if($lock && (int)$lock['csr_id']!==$csrId && !isCsrManager($db,$csrId)) { echo json_encode(['success'=>false,'message'=>'This ticket is locked by another CSR.']); exit; }
 $zip=trim($_POST['zip_code']??''); $meta=$zip?getZipAddressMeta($db,$zip):null;
 $cityId=(int)($_POST['city_id']??0); $cityName=trim($_POST['city']??''); $state=trim($_POST['state']??''); $region=trim($_POST['region']??'');
 if($meta){ $cityId=(int)($meta['city_id'] ?? 0); $cityName=$meta['city_name']; $state=$meta['state']; $region=$region ?: $meta['region']; }
 if(!$cityId && $cityName!=='' && $state!==''){
   $q=$db->prepare("SELECT id FROM cities WHERE LOWER(city_name)=LOWER(:city) AND LOWER(state)=LOWER(:state) LIMIT 1"); $q->execute([':city'=>$cityName,':state'=>$state]); $cityId=(int)$q->fetchColumn();
   if(!$cityId){ $ins=$db->prepare("INSERT INTO cities (city_name, region, state, is_active) VALUES (:city,:region,:state,1)"); $ins->execute([':city'=>$cityName,':region'=>$region,':state'=>$state]); $cityId=(int)$db->lastInsertId(); }
 }
 $brand=trim($_POST['brand']??''); $appliance=trim($_POST['appliance_type']??'');
 $brandId=null; if($brand!==''){ $s=$db->prepare("SELECT id FROM brands WHERE LOWER(name)=LOWER(:n) LIMIT 1"); $s->execute([':n'=>$brand]); $brandId=$s->fetchColumn()?:null; }
 $applianceId=null; if($appliance!==''){ $s=$db->prepare("SELECT id FROM appliance_types WHERE LOWER(name)=LOWER(:n) LIMIT 1"); $s->execute([':n'=>$appliance]); $applianceId=$s->fetchColumn()?:null; }
 $stmt=$db->prepare("UPDATE service_requests SET
   full_name=:full_name, phone_number=:phone_number, secondary_phone=:secondary_phone, customer_email=:customer_email,
   service_address=:service_address, service_address_2=:service_address_2, region=:region, city_id=:city_id, state=:state, zip_code=:zip_code, landmark=:landmark,
   brand_id=:brand_id, manual_brand=:manual_brand, appliance_type_id=:appliance_type_id, manual_appliance_type=:manual_appliance_type,
   model_number=:model_number, serial_number=:serial_number, product_model_version=:product_model_version,
   purchase_date=:purchase_date, warranty_type=:warranty_type,
   issue_description=:issue_description, special_request=:special_request, preferred_date=:preferred_date, last_updated_at=NOW()
   WHERE id=:request_id");
 $stmt->execute([
  ':full_name'=>trim($_POST['full_name']??''), ':phone_number'=>trim($_POST['phone_number']??''), ':secondary_phone'=>trim($_POST['secondary_phone']??''), ':customer_email'=>trim($_POST['customer_email']??''),
  ':service_address'=>trim($_POST['service_address']??''), ':service_address_2'=>trim($_POST['service_address_2']??''), ':region'=>$region, ':city_id'=>$cityId?:null, ':state'=>$state, ':zip_code'=>$zip, ':landmark'=>trim($_POST['landmark']??''),
  ':brand_id'=>$brandId, ':manual_brand'=>$brandId?null:$brand, ':appliance_type_id'=>$applianceId, ':manual_appliance_type'=>$applianceId?null:$appliance,
  ':model_number'=>trim($_POST['model_number']??''), ':serial_number'=>trim($_POST['serial_number']??''), ':product_model_version'=>trim($_POST['product_model_version']??''),
  ':purchase_date'=>($_POST['purchase_date']??'')?:null, ':warranty_type'=>trim($_POST['warranty_type']??''),
  ':issue_description'=>trim($_POST['issue_description']??''), ':special_request'=>trim($_POST['special_request']??''), ':preferred_date'=>($_POST['preferred_date']??'')?:null, ':request_id'=>$requestId
 ]);
 logRequestAction($db,$requestId,$csrId,'csr','details_update',null,'updated','CSR edited request details');
 echo json_encode(['success'=>true,'message'=>'Request details updated.']);
} catch(Exception $e){ echo json_encode(['success'=>false,'message'=>$e->getMessage()]); }
