<?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'];
requirePermission($conn,'customers','add');
$mode=$_POST['mode'] ?? 'preview';
if(empty($_FILES['file']['tmp_name'])) jsonResponse(false,'Choose CSV file');
$fh=fopen($_FILES['file']['tmp_name'],'r'); if(!$fh) jsonResponse(false,'Cannot read file');
$headers=fgetcsv($fh); if(!$headers) jsonResponse(false,'Empty file');
$headers=array_map(fn($h)=>strtolower(trim($h)), $headers);
$rows=[]; $n=1;
while(($data=fgetcsv($fh))!==false){ $n++; $row=[]; foreach($headers as $i=>$h) $row[$h]=trim($data[$i] ?? ''); if(!implode('',$row)) continue; $rows[]=['n'=>$n,'row'=>$row]; }
$result=[]; $inserted=0;
foreach($rows as $r){
  $row=$r['row']; $name=sanitize($conn,$row['customer_name'] ?? ''); $phone=sanitize($conn,$row['phone'] ?? ''); $email=sanitize($conn,$row['email'] ?? '');
  $errors=[]; if(!$name) $errors[]='Missing customer_name';
  if($phone){ $q=$conn->query("SELECT id FROM customers WHERE account_id=$account_id AND phone='$phone' LIMIT 1"); if($q&&$q->num_rows)$errors[]='Phone exists'; }
  if($email){ $q=$conn->query("SELECT id FROM customers WHERE account_id=$account_id AND email='$email' LIMIT 1"); if($q&&$q->num_rows)$errors[]='Email exists'; }
  if(!$errors && $mode==='submit'){
    $business=sanitize($conn,$row['business_name'] ?? ''); $country=(int)($row['country_id'] ?? 0); $countrySql=$country?:'NULL'; $address=sanitize($conn,$row['address'] ?? ''); $notes=sanitize($conn,$row['notes'] ?? ''); $priority=(int)($row['priority'] ?? 3); if($priority<1||$priority>5)$priority=3;
    $source_id='NULL'; $source=sanitize($conn,$row['source'] ?? '');
    if($source && tableExists($conn,'customer_sources')){ $sq=$conn->query("SELECT id FROM customer_sources WHERE account_id=$account_id AND name='$source' LIMIT 1"); if($sq&&$sq->num_rows)$source_id=(int)$sq->fetch_assoc()['id']; else { $conn->query("INSERT INTO customer_sources (account_id,name,status) VALUES ($account_id,'$source',1)"); $source_id=(int)$conn->insert_id; } }
    $conn->query("INSERT INTO customers (customer_name,business_name,phone,email,country_id,address,notes,priority,source_id,account_id,created_by_user_id,date_created) VALUES ('$name','$business','$phone','$email',$countrySql,'$address','$notes',$priority,$source_id,$account_id,$user_id,NOW())");
    $inserted++;
  }
  $result[]=['row'=>$r['n'],'name'=>$name,'phone'=>$phone,'email'=>$email,'status'=>$errors?'error':($mode==='submit'?'inserted':'ready'),'message'=>$errors?implode(', ',$errors):'OK'];
}
jsonResponse(true,$mode==='submit'?"Imported $inserted customers":'Preview ready',['rows'=>$result,'inserted'=>$inserted]);
