<?php
// Error Reporting On - ताकि सफेद पेज के बजाय एरर दिखे
ini_set('display_errors', 1);
error_reporting(E_ALL);

if (!defined('BASEPATH')) exit('No direct script access allowed');

// [ 1. SEEN LOGIC ]
if (isset($_GET['action']) && $_GET['action'] == "mark_note_seen") {
    $uid = $_SESSION["msmbilisim_userid"]; 
    if($uid){
        $conn->prepare("UPDATE admin_notes SET is_seen = 1, status = 'seen' WHERE client_id = ? AND is_seen = 0")->execute([$uid]);
    }
    header("Content-Type: application/json");
    echo json_encode(['status' => 'success']);
    exit;
}

// [ 2. DELETE & RESEND LOGIC ]
if(route(2) == "delete" && is_numeric(route(3))){
    $conn->prepare("DELETE FROM admin_notes WHERE id = ?")->execute([route(3)]);
    header("Location: " . site_url('admin/user-note'));
    exit;
}
if(route(2) == "resend" && is_numeric(route(3))){
    $conn->prepare("UPDATE admin_notes SET is_seen = 0, status = 'pending' WHERE id = ?")->execute([route(3)]);
    header("Location: " . site_url('admin/user-note'));
    exit;
}

// [ 3. POST LOGIC ]
if ($_POST) {
    $client_id = $_POST['client_id'];
    $note_text = $_POST['note_text'];
    if(!empty($client_id) && !empty($note_text)){
        $conn->prepare("DELETE FROM admin_notes WHERE client_id = ?")->execute([$client_id]);
        $conn->prepare("INSERT INTO admin_notes (client_id, note_text, is_seen, status) VALUES (?, ?, 0, 'pending')")->execute([$client_id, $note_text]);
        echo "success";
        exit;
    }
}

// [ 4. DATA FETCHING ]
$clients = $conn->query("SELECT client_id, username FROM clients ORDER BY username ASC")->fetchAll(PDO::FETCH_ASSOC);
$notes_history = $conn->query("SELECT n.*, c.username FROM admin_notes n INNER JOIN clients c ON c.client_id = n.client_id ORDER BY n.id DESC LIMIT 50")->fetchAll(PDO::FETCH_ASSOC);

// [ 5. LOAD VIEW - Path को एकदम सरल कर दिया है ]
require 'admin/views/user-note.php';