<?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':
    requirePermission($conn, 'reminders', ($_POST['edit_id'] ?? 0) ? 'edit' : 'add');
    $comment      = sanitize($conn, $_POST['comment'] ?? '');
    $date         = sanitize($conn, $_POST['date'] ?? date('Y-m-d'));
    $time         = sanitize($conn, $_POST['time'] ?? '');
    $cust_id      = (int)($_POST['customer_id'] ?? 0) ?: 'NULL';
    $lead_id      = (int)($_POST['lead_id'] ?? 0) ?: 'NULL';
    $uid          = (int)($_POST['user_id'] ?? $user_id);
    $act_type_id  = (int)($_POST['activity_type_id'] ?? 0) ?: 'NULL';
    $edit_id      = (int)($_POST['edit_id'] ?? 0);
    $time_val     = $time ? "'$time'" : 'NULL';
    if (!$comment || !$date) jsonResponse(false, 'Comment and date required');
    if ($edit_id) {
      $conn->query("UPDATE reminder SET comment='$comment', date='$date', time=$time_val, customer_id=$cust_id, lead_id=$lead_id, user_id=$uid, activity_type_id=$act_type_id WHERE id=$edit_id AND account_id=$account_id");
    } else {
      $conn->query("INSERT INTO reminder (comment, date, time, customer_id, lead_id, user_id, activity_type_id, account_id) VALUES ('$comment','$date',$time_val,$cust_id,$lead_id,$uid,$act_type_id,$account_id)");
    }
    jsonResponse(true, $edit_id ? 'Updated' : 'Reminder added');
  case 'get':
    $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
    $r  = $conn->query("SELECT * FROM reminder WHERE id=$id AND account_id=$account_id")->fetch_assoc();
    if (!$r) jsonResponse(false, 'Not found');
    jsonResponse(true, '', ['data' => $r]);
  case 'done':
    requirePermission($conn, 'reminders', 'done');
    $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
    $conn->query("UPDATE reminder SET status='done', finish_at=NOW() WHERE id=$id AND account_id=$account_id");
    jsonResponse(true, 'Marked as done');
  case 'delete':
    requirePermission($conn, 'reminders', 'delete');
    $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
    $conn->query("DELETE FROM reminder WHERE id=$id AND account_id=$account_id");
    jsonResponse(true, 'Deleted');
  default:
    jsonResponse(false, 'Invalid action');
}
