<?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    = $_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':
    $title       = sanitize($conn, $_POST['title'] ?? '');
    $customer_id = (int)($_POST['customer_id'] ?? 0);
    $item_id     = (int)($_POST['item_id'] ?? 0) ?: 'NULL';
    $stage_id    = (int)($_POST['stage_id'] ?? 0) ?: 'NULL';
    $priority    = (int)($_POST['priority'] ?? 3);
    $opportunity = (int)($_POST['opportunity'] ?? 50);
    $est_price   = (float)($_POST['estimated_price'] ?? 0);
    $assigned    = (int)($_POST['assigned_user_id'] ?? 0) ?: 'NULL';
    $status      = sanitize($conn, $_POST['status'] ?? 'open');
    $note        = sanitize($conn, $_POST['note'] ?? '');
    $edit_id     = (int)($_POST['edit_id'] ?? 0);
    $forceDuplicate = (int)($_POST['force_duplicate'] ?? 0);
    $opportunity = max(0, min(100, round($opportunity / 25) * 25));
    if (!$customer_id) jsonResponse(false, 'Customer required');
    if ($item_id !== 'NULL') {
      $dup = $conn->query("SELECT id FROM leads WHERE account_id=$account_id AND customer_id=$customer_id AND item_id=$item_id AND datetime_deleted IS NULL" . ($edit_id ? " AND id<>$edit_id" : "") . " LIMIT 1");
      if ($dup && $dup->num_rows && !$forceDuplicate) jsonResponse(false, 'DUPLICATE_LEAD_ITEM: This customer already has a lead for this item. Submit again if you still want to save it.');
    }
    if ($edit_id) {
      requirePermission($conn, 'leads', 'edit');
      $conn->query("UPDATE leads SET title='$title', customer_id=$customer_id, item_id=$item_id, stage_id=$stage_id, priority=$priority, opportunity=$opportunity, estimated_price=$est_price, assigned_user_id=$assigned, status='$status', note='$note' WHERE id=$edit_id AND account_id=$account_id");
      jsonResponse(true, 'Lead updated', ['id' => $edit_id]);
    } else {
      requirePermission($conn, 'leads', 'add');
      $createdByCol = columnExists($conn, 'leads', 'created_by_user_id') ? ', created_by_user_id' : '';
      $createdByVal = columnExists($conn, 'leads', 'created_by_user_id') ? ', ' . $user_id : '';
      $conn->query("INSERT INTO leads (title, customer_id, item_id, stage_id, priority, opportunity, estimated_price, assigned_user_id, status, note, account_id$createdByCol) VALUES ('$title',$customer_id,$item_id,$stage_id,$priority,$opportunity,$est_price,$assigned,'$status','$note',$account_id$createdByVal)");
      $newLeadId = (int)$conn->insert_id;
      if ($newLeadId && columnExists($conn, 'lead_activities', 'date_activitie')) {
        $conn->query("INSERT INTO lead_activities (lead_id, user_id, text, activity_type_id, date_activitie) VALUES ($newLeadId,$user_id,'Lead created',6,CURDATE())");
      }
      jsonResponse(true, 'Lead added', ['id' => $newLeadId]);
    }
    
    
    case 'update_status':
    $lead_id = (int)($json['lead_id'] ?? $_POST['lead_id'] ?? 0);
    $status = sanitize($conn, $json['status'] ?? $_POST['status'] ?? '');
    if (!in_array($status, ['open', 'won', 'lost'])) {
        jsonResponse(false, 'Invalid status');
    }
    $chk = $conn->query("SELECT id FROM leads WHERE id=$lead_id AND account_id=$account_id");
    if (!$chk->num_rows) jsonResponse(false, 'Unauthorized');
    $conn->query("UPDATE leads SET status='$status' WHERE id=$lead_id AND account_id=$account_id");
    $conn->query("INSERT INTO lead_activities (lead_id, user_id, text, activity_type_id) VALUES ($lead_id, $user_id, 'Status changed to $status', 1)");
    jsonResponse(true, 'Status updated');
    break;
    
    
    
  case 'get':
    $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
    $r  = $conn->query("SELECT l.*, c.customer_name, i.name as item_name, s.name as stage_name, u.name as assigned_name FROM leads l LEFT JOIN customers c ON l.customer_id=c.id LEFT JOIN items i ON l.item_id=i.id LEFT JOIN stage s ON l.stage_id=s.id LEFT JOIN users u ON l.assigned_user_id=u.id WHERE l.id=$id AND l.account_id=$account_id")->fetch_assoc();
    if (!$r) jsonResponse(false, 'Not found');
    jsonResponse(true, '', ['data' => $r]);

  case 'get_full':
    $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
    $r  = $conn->query("SELECT l.*, c.customer_name, i.name as item_name, s.name as stage_name, s.color as stage_color, u.name as assigned_name FROM leads l LEFT JOIN customers c ON l.customer_id=c.id LEFT JOIN items i ON l.item_id=i.id LEFT JOIN stage s ON l.stage_id=s.id LEFT JOIN users u ON l.assigned_user_id=u.id WHERE l.id=$id AND l.account_id=$account_id")->fetch_assoc();
    if (!$r) jsonResponse(false, 'Not found');
    $fq = $conn->query("SELECT f.*, u.name as user_name FROM lead_followup f LEFT JOIN users u ON f.user_id=u.id WHERE f.lead_id=$id ORDER BY f.datetime DESC LIMIT 20");
    $followups = []; while ($f = $fq->fetch_assoc()) $followups[] = $f;
    $aq = $conn->query("SELECT a.*, u.name as user_name, at.name as type_name FROM lead_activities a LEFT JOIN users u ON a.user_id=u.id LEFT JOIN activity_type at ON a.activity_type_id=at.id WHERE a.lead_id=$id ORDER BY a.datetime DESC LIMIT 20");
    $activities = []; while ($a = $aq->fetch_assoc()) $activities[] = $a;
    jsonResponse(true, '', ['data' => $r, 'followups' => $followups, 'activities' => $activities]);

  case 'save_note':
    $id   = (int)($json['id'] ?? $_POST['id'] ?? 0);
    $note = sanitize($conn, $json['note'] ?? $_POST['note'] ?? '');
    $chk  = $conn->query("SELECT id FROM leads WHERE id=$id AND account_id=$account_id");
    if (!$chk->num_rows) jsonResponse(false, 'Unauthorized');
    $conn->query("UPDATE leads SET note='$note' WHERE id=$id AND account_id=$account_id");
    jsonResponse(true, 'Note saved');

  case 'add_followup':
    $lead_id = (int)($json['lead_id'] ?? $_POST['lead_id'] ?? 0);
    $comment = sanitize($conn, $json['comment'] ?? $_POST['comment'] ?? '');
    if (!$comment) jsonResponse(false, 'Comment required');
    $chk = $conn->query("SELECT id FROM leads WHERE id=$lead_id AND account_id=$account_id");
    if (!$chk->num_rows) jsonResponse(false, 'Unauthorized');
    $conn->query("INSERT INTO lead_followup (lead_id, user_id, comment) VALUES ($lead_id, $user_id, '$comment')");
    jsonResponse(true, 'Comment added');

//   case 'add_activity':
//     $lead_id = (int)($json['lead_id'] ?? $_POST['lead_id'] ?? 0);
//     $text    = sanitize($conn, $json['text'] ?? $_POST['text'] ?? '');
//     $actdate    = sanitize($conn, $json['actdate'] ?? $_POST['actdate'] ?? '');
//     echo $actdate;
//     $type_id = (int)($json['activity_type_id'] ?? $_POST['activity_type_id'] ?? 1);
//     $chk = $conn->query("SELECT id FROM leads WHERE id=$lead_id AND account_id=$account_id");
//     if (!$chk->num_rows) jsonResponse(false, 'Unauthorized');
//     $conn->query("INSERT INTO lead_activities (lead_id, user_id, text, activity_type_id , date_activitie) VALUES ($lead_id, $user_id, '$text', $type_id , $actdate)");
//     jsonResponse(true, 'Activity logged');

case 'add_activity':
    requirePermission($conn, 'leads', 'take_action');
    $lead_id = (int)($json['lead_id'] ?? $_POST['lead_id'] ?? 0);
    if (!$lead_id) jsonResponse(false, 'Lead ID missing');
    $text = sanitize($conn, $json['text'] ?? $_POST['text'] ?? '');
    if (!$text) jsonResponse(false, 'Activity text missing');
    $type_id = (int)($json['activity_type_id'] ?? $_POST['activity_type_id'] ?? 1);
    $account_id = $_SESSION['account_id'] ?? 0;
    $user_id    = $_SESSION['user_id'] ?? 0;
    if (!$account_id || !$user_id) jsonResponse(false, 'Unauthorized');
    $actdate_raw = $json['actdate'] ?? $_POST['actdate'] ?? '';
    if (!$actdate_raw) jsonResponse(false, 'Activity date missing');
    $dt = DateTime::createFromFormat('Y-m-d', $actdate_raw);
    if (!$dt) {
        $dt = DateTime::createFromFormat('d/m/Y', $actdate_raw);
        if (!$dt) jsonResponse(false, 'Invalid date format');
    }
    $actdate = $dt->format('Y-m-d');
    $chk = $conn->prepare("SELECT id FROM leads WHERE id=? AND account_id=?");
    $chk->bind_param("ii", $lead_id, $account_id);
    $chk->execute();
    $chk->store_result();
    if ($chk->num_rows === 0) jsonResponse(false, 'Unauthorized');
    $activity_comment = sanitize($conn, $json['comment'] ?? $_POST['comment'] ?? $text);
    if (columnExists($conn, 'lead_activities', 'comment')) {
        $stmt = $conn->prepare("INSERT INTO lead_activities (lead_id, user_id, text, comment, activity_type_id, date_activitie) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("iissis", $lead_id, $user_id, $text, $activity_comment, $type_id, $actdate);
    } else {
        $stmt = $conn->prepare("INSERT INTO lead_activities (lead_id, user_id, text, activity_type_id, date_activitie) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("iisis", $lead_id, $user_id, $text, $type_id, $actdate);
    }
    if ($stmt->execute()) {
        $makeReminder = (int)($json['make_reminder'] ?? $_POST['make_reminder'] ?? 0);
        if ($makeReminder || ($actdate && $actdate >= date('Y-m-d'))) {
            $leadInfo = $conn->query("SELECT customer_id FROM leads WHERE id=$lead_id AND account_id=$account_id LIMIT 1")->fetch_assoc();
            $customerSql = $leadInfo ? (int)$leadInfo['customer_id'] : 'NULL';
            $conn->query("INSERT INTO reminder (`date`, `time`, `comment`, `customer_id`, `lead_id`, `user_id`, `activity_type_id`, `status`, `account_id`) VALUES ('$actdate', NULL, '$activity_comment', $customerSql, $lead_id, $user_id, $type_id, 'pending', $account_id)");
        }
        jsonResponse(true, 'Activity logged');
    } else {
        jsonResponse(false, 'Failed to log activity');
    }

    break;
    
    

case 'add_reminder':
    requirePermission($conn, 'reminders', 'add');

    $lead_id = (int)($json['lead_id'] ?? $_POST['lead_id'] ?? 0);

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

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

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

    $activity_type_id = (int)(
        $json['activity_type_id']
        ?? $_POST['activity_type_id']
        ?? 0
    );

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

    if (!$lead_id) {
        jsonResponse(false, 'Invalid lead');
    }

    if (!$date) {
        jsonResponse(false, 'Reminder date required');
    }

    if (!$comment) {
        jsonResponse(false, 'Reminder note required');
    }

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

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

    $lead = $leadQ->fetch_assoc();

    $customer_id = (int)$lead['customer_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,
            $lead_id,
            $user_id,
            $typeSql,
            'pending',
            $account_id
        )
    ";

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

    jsonResponse(true, 'Reminder added');

    break;
    
  case 'move_stage':
    requirePermission($conn, 'leads', 'move_stage');
    $lead_id  = (int)($json['lead_id'] ?? $_POST['lead_id'] ?? 0);
    $stage_id = (int)($json['stage_id'] ?? $_POST['stage_id'] ?? 0);
    $sc = $conn->query("SELECT name FROM stage WHERE id=$stage_id AND account_id=$account_id");
    if (!$sc->num_rows) jsonResponse(false, 'Invalid stage');
    $sn = $conn->real_escape_string($sc->fetch_assoc()['name']);
    $oldQ = $conn->query("SELECT stage_id FROM leads WHERE id=$lead_id AND account_id=$account_id LIMIT 1");
    if (!$oldQ || !$oldQ->num_rows) jsonResponse(false, 'Lead not found');
    $from_stage_id = (int)$oldQ->fetch_assoc()['stage_id'];
    $conn->query("UPDATE leads SET stage_id=$stage_id WHERE id=$lead_id AND account_id=$account_id");
    if (tableExists($conn, 'lead_stage_history')) {
      $conn->query("INSERT INTO lead_stage_history (lead_id, account_id, user_id, from_stage_id, to_stage_id, moved_at) VALUES ($lead_id, $account_id, $user_id, ".($from_stage_id ?: 'NULL').", $stage_id, NOW())");
    }
    $conn->query("INSERT INTO lead_activities (lead_id, user_id, text, activity_type_id, date_activitie) VALUES ($lead_id, $user_id, 'Moved to $sn', 1, CURDATE())");
    jsonResponse(true, 'Stage updated', ['stage_name' => $sn, 'moved_at' => date('Y-m-d H:i:s')]);

  case 'delete':
    requirePermission($conn, 'leads', 'delete');
    $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
    $conn->query("UPDATE leads SET datetime_deleted = NOW() WHERE id = $id AND account_id = $account_id");
    jsonResponse(true, 'Lead deleted');
    break;

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