<?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();
}

$request_id = isset($_POST['request_id']) ? (int)$_POST['request_id'] : 0;
$note_type = isset($_POST['note_type']) ? $_POST['note_type'] : 'csr_note';
$note_content = isset($_POST['note_content']) ? trim($_POST['note_content']) : '';
$notify_customer = isset($_POST['notify_customer']) ? (int)$_POST['notify_customer'] : 0;
$follow_up_reminder = isset($_POST['follow_up_reminder']) ? trim($_POST['follow_up_reminder']) : '';

if (!$request_id || empty($note_content)) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit();
}

$database = new Database();
$db = $database->getConnection();
ensureOperationalTables($db);
ensureUnifiedTicketWorkflow($db);
ensureCsrTeamTables($db);
requireCsrRequestAccessJson($db, (int)$_SESSION['csr_id'], $request_id);

$lockResult = blockIfRequestLockedByOtherCSR($db, $request_id, $_SESSION['csr_id']);
if (!$lockResult['success']) {
    echo json_encode($lockResult);
    exit();
}

$allowed_note_types = ['internal', 'customer', 'csr_note'];
if (!in_array($note_type, $allowed_note_types, true)) { $note_type = 'internal'; }

// Insert note
$query = "INSERT INTO request_notes (request_id, csr_id, note_type, note_content, notified_customer) 
          VALUES (:request_id, :csr_id, :note_type, :note_content, :notified_customer)";
$stmt = $db->prepare($query);
$stmt->bindValue(':request_id', $request_id);
$stmt->bindValue(':csr_id', $_SESSION['csr_id']);
$stmt->bindValue(':note_type', $note_type);
$stmt->bindValue(':note_content', $note_content);
$stmt->bindValue(':notified_customer', $notify_customer);

if ($stmt->execute()) {
    if ($follow_up_reminder !== '') {
        $upd = $db->prepare("UPDATE service_requests SET follow_up_reminder = :reminder, follow_up_due_at = NULL, last_updated_at = NOW() WHERE id = :request_id");
        $upd->execute([':reminder' => $follow_up_reminder, ':request_id' => $request_id]);
    } else {
        $db->prepare("UPDATE service_requests SET last_updated_at = NOW() WHERE id = :request_id")->execute([':request_id' => $request_id]);
    }
    logRequestAction($db, $request_id, $_SESSION['csr_id'], 'csr', 'note_added', null, $note_type, ($follow_up_reminder ? 'Follow-Up: ' . $follow_up_reminder . "\n" : '') . $note_content);
    logCSRActivity($db, $_SESSION['csr_id'], 'note_added', $request_id, $note_type);
    // If this is a customer-facing update and notify is checked, create an in-app customer notification.
    // This does NOT send email. The customer will see it in Customer Dashboard > Notifications
    // and can open their own request from My Requests.
    if ($note_type === 'customer' && $notify_customer) {
        $db->exec("CREATE TABLE IF NOT EXISTS notifications (
            id INT AUTO_INCREMENT PRIMARY KEY,
            customer_id INT NOT NULL,
            title VARCHAR(255) NOT NULL,
            message TEXT NULL,
            type ENUM('info','success','warning','danger') DEFAULT 'info',
            link VARCHAR(255) DEFAULT NULL,
            is_read TINYINT(1) DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            read_at TIMESTAMP NULL DEFAULT NULL,
            INDEX idx_notifications_customer_read (customer_id, is_read),
            INDEX idx_notifications_created (created_at)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

        $query = "SELECT sr.customer_id, sr.request_number, c.first_name
                  FROM service_requests sr
                  LEFT JOIN customers c ON sr.customer_id = c.id
                  WHERE sr.id = :request_id AND sr.customer_id IS NOT NULL
                  LIMIT 1";
        $stmt = $db->prepare($query);
        $stmt->execute([':request_id' => $request_id]);
        $customer = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($customer && !empty($customer['customer_id'])) {
            $shortNote = trim(preg_replace('/\s+/', ' ', $note_content));
            if (function_exists('mb_strlen') && mb_strlen($shortNote) > 180) {
                $shortNote = mb_substr($shortNote, 0, 177) . '...';
            } elseif (strlen($shortNote) > 180) {
                $shortNote = substr($shortNote, 0, 177) . '...';
            }

            $notif = $db->prepare("INSERT INTO notifications (customer_id, title, message, type, link, is_read, created_at)
                                   VALUES (:customer_id, :title, :message, 'info', :link, 0, NOW())");
            $notif->execute([
                ':customer_id' => (int)$customer['customer_id'],
                ':title' => 'New Customer Update',
                ':message' => 'A new update was added to your request #' . ($customer['request_number'] ?: $request_id) . ': ' . $shortNote,
                ':link' => 'my_requests.php?request_id=' . $request_id
            ]);

            logRequestAction($db, $request_id, $_SESSION['csr_id'], 'csr', 'customer_notified', null, 'in_app_notification', 'Customer notification sent from Customer Updates note.');
        }
    }
    
    echo json_encode(['success' => true, 'message' => ($note_type === 'customer' && $notify_customer) ? 'Customer update saved and notification sent.' : 'Note added successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to add note']);
}
?>