<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();

include __DIR__ . '/../inc/db.php'; // Adjust path if needed

$action = $_POST['action'] ?? '';

if ($action === 'insert') {
    $inquiry_id = $_POST['inquiry_id'];
    $followup_date = date('Y-m-d H:i:s');
    $followup_mode = $_POST['followup_mode'];
    $remarks = $_POST['followup_remarks'];
    $status = $_POST['followup_status'];
    $next_followup_date = !empty($_POST['reschedule_date']) ? $_POST['reschedule_date'] : null;
    $followed_by = $_POST['user_id'] ?? $_SESSION['user_id'] ?? 1;

    $query = "INSERT INTO inquiry_followups 
              (inquiry_id, followup_date, followup_mode, remarks, status, next_followup_date, followed_by) 
              VALUES (?, ?, ?, ?, ?, ?, ?)";

    $stmt = $conn->prepare($query);
    $stmt->bind_param("isssssi", $inquiry_id, $followup_date, $followup_mode, $remarks, $status, $next_followup_date, $followed_by);

    if ($stmt->execute()) {
        $inquiry_followup_status = ($status === 'pending' || $status === 'rescheduled') ? 'pending' : $status;
        $updateQuery = "UPDATE inquiries SET followup_status = ?, last_followup_date = ?, last_followup_update = ?, next_followup_date = ? WHERE id = ?";
        $updateStmt = $conn->prepare($updateQuery);
        $updateStmt->bind_param("ssssi", $inquiry_followup_status, $followup_date, $remarks,$next_followup_date, $inquiry_id);
        $updateStmt->execute();

        echo json_encode(['success' => true, 'message' => 'Follow-up successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Insert failed']);
    }
    exit;
}


if ($action === 'fetch') {
    $inquiry_id = intval($_POST['inquiry_id']);

    $query = "SELECT f.inquiry_id,
      f.followup_date, 
      f.followup_mode, 
      f.remarks, 
      f.status, 
      f.next_followup_date,
      u.name AS followed_by_name
    FROM inquiry_followups f
    JOIN users u ON f.followed_by = u.id
    WHERE f.inquiry_id = ?
    ORDER BY f.followup_date DESC";

    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $inquiry_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[] = [
            'followup_date' => date('d-m-Y H:i', strtotime($row['followup_date'])),
            'followup_mode' => ucfirst($row['followup_mode']),
            'remarks' => htmlspecialchars($row['remarks']),
            'status' => ucfirst($row['status']),
            'next_followup_date' => !empty($row['next_followup_date']) ? date('d-m-Y', strtotime($row['next_followup_date'])) : 'N/A',
            'followed_by_name' => ucwords($row['followed_by_name'])
        ];
    }

    echo json_encode($data);
    exit;
}
?>
