<?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 = $_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 'add':
  case 'edit':
    $name     = sanitize($conn, $_POST['customer_name'] ?? '');
    $business = sanitize($conn, $_POST['business_name'] ?? '');
    $phone    = sanitize($conn, $_POST['phone'] ?? '');
    $email    = sanitize($conn, $_POST['email'] ?? '');
    $country_id = $_POST['country_id'] ? (int)$_POST['country_id'] : null;
    $address  = sanitize($conn, $_POST['address'] ?? '');
    $notes    = sanitize($conn, $_POST['notes'] ?? '');
    $priority = (int)($_POST['priority'] ?? 3);
    $source_id = isset($_POST['source_id']) && $_POST['source_id'] !== '' ? (int)$_POST['source_id'] : null;
    $edit_id  = (int)($_POST['edit_id'] ?? 0);
    
    if (!$name) jsonResponse(false, 'Customer name required');
    
    if ($edit_id) {
      requirePermission($conn, 'customers', 'edit');
      $conn->query("UPDATE customers SET 
        customer_name='$name', 
        business_name='$business', 
        phone='$phone', 
        email='$email', 
        country_id=" . ($country_id ? $country_id : 'NULL') . ", 
        address='$address',
        notes='$notes', 
        priority=$priority,
        source_id=" . ($source_id ? $source_id : 'NULL') . "
        WHERE id=$edit_id AND account_id=$account_id");
      $cust_id = $edit_id;
      
      // Delete existing contacts and re-add
      $conn->query("DELETE FROM customer_contacts WHERE customer_id=$cust_id");
    } else {
      requirePermission($conn, 'customers', 'add');
      $createdByCol = columnExists($conn, 'customers', 'created_by_user_id') ? ', created_by_user_id' : '';
      $createdByVal = columnExists($conn, 'customers', 'created_by_user_id') ? ', ' . $user_id : '';
      $conn->query("INSERT INTO customers (customer_name, business_name, phone, email, country_id, address, notes, priority, source_id, account_id$createdByCol) 
        VALUES ('$name','$business','$phone','$email'," . ($country_id ? $country_id : 'NULL') . ",'$address','$notes',$priority," . ($source_id ? $source_id : 'NULL') . ",$account_id$createdByVal)");
      $cust_id = $conn->insert_id;
    }
    
    $contacts = $_POST['contacts'] ?? [];
    foreach ($contacts as $c) {
      $cn  = sanitize($conn, $c['name'] ?? '');
      $cjt = sanitize($conn, $c['job_title'] ?? '');
      $cp  = sanitize($conn, $c['phone'] ?? '');
      $ce  = sanitize($conn, $c['email'] ?? '');
      if ($cn) $conn->query("INSERT INTO customer_contacts (name, job_title, phone, email, customer_id) VALUES ('$cn','$cjt','$cp','$ce',$cust_id)");
    }
    jsonResponse(true, $edit_id ? 'Customer updated' : 'Customer added', ['id' => $cust_id]);
    
  case 'get':
    $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
    $r  = $conn->query("SELECT c.*, co.name as country_name, co.phone_code 
      FROM customers c 
      LEFT JOIN countries co ON co.id = c.country_id 
      WHERE c.id=$id AND c.account_id=$account_id")->fetch_assoc();
    if (!$r) jsonResponse(false, 'Not found');
    $cq = $conn->query("SELECT * FROM customer_contacts WHERE customer_id=$id ORDER BY id");
    $contacts = [];
    while ($c = $cq->fetch_assoc()) $contacts[] = $c;
    jsonResponse(true, '', ['data' => $r, 'contacts' => $contacts]);
    
//   case 'delete':
//     $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
//     $conn->query("DELETE FROM customers WHERE id=$id AND account_id=$account_id");
//     jsonResponse(true, 'Customer deleted');



case 'add_reminder':
    requirePermission($conn, 'reminders', 'add');
    $customer_id = (int)($_POST['customer_id'] ?? $json['customer_id'] ?? 0);
    $lead_id = (int)($_POST['lead_id'] ?? $json['lead_id'] ?? 0);
    $activity_type_id = (int)($_POST['activity_type_id'] ?? $json['activity_type_id'] ?? 0);

    $date = sanitize($conn, $_POST['date'] ?? $json['date'] ?? '');
    $time = sanitize($conn, $_POST['time'] ?? $json['time'] ?? '');
    $comment = sanitize($conn, $_POST['comment'] ?? $json['comment'] ?? '');

    $user_id = (int)$_SESSION['user_id'];

    if (!$customer_id) jsonResponse(false, 'Invalid customer');
    if (!$date) jsonResponse(false, 'Reminder date required');
    if (!$comment) jsonResponse(false, 'Reminder comment required');

    $chk = $conn->query("
        SELECT id
        FROM customers
        WHERE id = $customer_id
          AND account_id = $account_id
        LIMIT 1
    ");

    if (!$chk || $chk->num_rows === 0) {
        jsonResponse(false, 'Customer not found');
    }

    $leadSql = "NULL";

    if ($lead_id) {
        $leadChk = $conn->query("
            SELECT id
            FROM leads
            WHERE id = $lead_id
              AND customer_id = $customer_id
              AND account_id = $account_id
              AND datetime_deleted IS NULL
            LIMIT 1
        ");

        if (!$leadChk || $leadChk->num_rows === 0) {
            jsonResponse(false, 'Invalid lead for this customer');
        }

        $leadSql = $lead_id;
    }

    $timeSql = $time ? "'$time'" : "NULL";
    $typeSql = $activity_type_id ? $activity_type_id : "NULL";

    $q = "
        INSERT INTO reminder
        (`date`, `time`, `comment`, `customer_id`, `lead_id`, `user_id`, `activity_type_id`, `status`, `account_id`)
        VALUES
        ('$date', $timeSql, '$comment', $customer_id, $leadSql, $user_id, $typeSql, 'pending', $account_id)
    ";

    if (!$conn->query($q)) {
        jsonResponse(false, $conn->error);
    }

    jsonResponse(true, 'Reminder added');
    break;
    
    
case 'delete':
  requirePermission($conn, 'customers', 'delete');
  $id = (int)($json['id'] ?? $_POST['id'] ?? 0);

  // tables يلي فيها customer_id وما لازم نحذف الزبون إذا مربوط فيها
  $checks = [
    'leads'              => 'Lead',
    'communications'     => 'Communication',
    'audience_customers' => 'Audience',
    'reminder'           => 'Reminder'
  ];

  foreach ($checks as $table => $label) {
    $q = $conn->query("SELECT id FROM `$table` WHERE customer_id=$id LIMIT 1");
    if ($q && $q->num_rows > 0) {
      jsonResponse(false, "Cannot delete customer. This customer is used in $label.");
    }
  }

  // contacts تابعين للزبون، فينا نحذفن عادي
  $conn->query("DELETE FROM customer_contacts WHERE customer_id=$id");

  $conn->query("DELETE FROM customers WHERE id=$id AND account_id=$account_id");

  jsonResponse(true, 'Customer deleted');
  
  
  
    
  default:
    jsonResponse(false, 'Invalid action');
}