<?php
header('Content-Type: application/json');
require 'db_connect.php';

$conn->set_charset("utf8mb4");
date_default_timezone_set('America/Caracas'); 

// Leer datos crudos (JSON)
$input = file_get_contents("php://input");
$data = json_decode($input);

// Capturar variables de forma segura
$action = $data->action ?? $_GET['action'] ?? '';
$uid = $conn->real_escape_string($data->user_id ?? $_GET['user_id'] ?? '');

// --- FUNCIONES ORIGINALES DE NOTIFICACIONES (TAL CUAL LAS TENÍAS) ---

if ($action === 'check_agenda_reminders') {
    $today = date('Y-m-d');
    $tomorrow = date('Y-m-d', strtotime('+1 day'));
    $sql = "SELECT client_name, delivery_date FROM orders WHERE user_id = '$uid' AND status != 'done' AND (delivery_date = '$today' OR delivery_date = '$tomorrow')";
    $res = $conn->query($sql);
    while($row = $res->fetch_assoc()) {
        $momento = ($row['delivery_date'] == $today) ? 'HOY' : 'MA&Ntilde;ANA';
        $msg = "Aviso: Entregar pedido de " . $row['client_name'] . " ($momento)";
        $check = $conn->query("SELECT id FROM notifications WHERE user_id = '$uid' AND message = '$msg' AND DATE(created_at) = '$today'");
        if ($check->num_rows == 0) {
            $conn->query("INSERT INTO notifications (user_id, sender_id, type, message) VALUES ('$uid', 'SISTEMA', 'agenda_alert', '$msg')");
        }
    }
    echo json_encode(["success" => true]);
    exit;
}

if ($action === 'list') {
    $sql = "SELECT n.*, u.name as sender_name, u.picture_url as sender_pic, u.custom_pic as sender_custom_pic 
            FROM notifications n LEFT JOIN users u ON n.sender_id = u.google_id 
            WHERE n.user_id = '$uid' ORDER BY n.created_at DESC LIMIT 15";
    $res = $conn->query($sql);
    $list = [];
    while($row = $res->fetch_assoc()) { 
        $type = trim($row['type']);
        $pid = $row['post_id'];
        if($row['sender_id'] === 'SISTEMA') {
            $row['target_url'] = 'agenda.html';
            $row['sender_name'] = 'EspacioApp';
            $row['sender_pic'] = 'https://cdn-icons-png.flaticon.com/512/3588/3588294.png';
        } else {
            $row['sender_pic'] = $row['sender_custom_pic'] ? $row['sender_custom_pic'] : $row['sender_pic'];
            if ($type == 'like' || $type == 'comment') { $row['target_url'] = "comunidad.html?post_id=$pid"; } 
            else if ($type == 'tip' || $type == 'greeting') { $row['target_url'] = "perfil.html?id=$uid"; } 
            else { $row['target_url'] = "perfil.html?id=" . $row['sender_id']; }
        }
        $list[] = $row; 
    }
    $conn->query("UPDATE notifications SET is_read = 1 WHERE user_id = '$uid'");
    echo json_encode($list);
    exit;
}

if ($action === 'get_unread_count') {
    $res = $conn->query("SELECT COUNT(*) as total FROM notifications WHERE user_id = '$uid' AND is_read = 0");
    echo json_encode(["total" => $res->fetch_assoc()['total']]);
    exit;
}

if ($action === 'clear_all') {
    $conn->query("DELETE FROM notifications WHERE user_id = '$uid'");
    echo json_encode(["success" => true]);
    exit;
}

// --- NUEVAS ACCIONES PARA LA AGENDA (USANDO LA COLUMNA 'product') ---

if ($action === 'get_orders') {
    // Usamos el alias delivery_date AS due_date para que el JS no se rompa
    $sql = "SELECT *, delivery_date AS due_date FROM orders WHERE user_id = '$uid' ORDER BY delivery_date ASC";
    $res = $conn->query($sql);
    $orders = [];
    while($row = $res->fetch_assoc()) { $orders[] = $row; }
    echo json_encode($orders);
    exit;
}

if ($action === 'create_order') {
    $cn = $conn->real_escape_string($data->client_name);
    $pd = $conn->real_escape_string($data->product); 
    $dd = $conn->real_escape_string($data->due_date);
    $pr = $conn->real_escape_string($data->price);
    $ph = $conn->real_escape_string($data->phone);
    
    // AQUÍ USAMOS 'product' QUE ES EL NOMBRE MÁS PROBABLE
    $sql = "INSERT INTO orders (user_id, client_name, product, delivery_date, price, phone, status) 
            VALUES ('$uid', '$cn', '$pd', '$dd', '$pr', '$ph', 'todo')";
    
    if($conn->query($sql)) echo json_encode(["success" => true]);
    else echo json_encode(["success" => false, "error" => $conn->error]);
    exit;
}

if ($action === 'update_order') {
    $oid = $conn->real_escape_string($data->order_id);
    $cn = $conn->real_escape_string($data->client_name);
    $pd = $conn->real_escape_string($data->product); 
    $dd = $conn->real_escape_string($data->due_date);
    $pr = $conn->real_escape_string($data->price);
    $ph = $conn->real_escape_string($data->phone);
    
    $sql = "UPDATE orders SET client_name='$cn', product='$pd', delivery_date='$dd', price='$pr', phone='$ph' 
            WHERE id='$oid' AND user_id='$uid'";
    
    if($conn->query($sql)) echo json_encode(["success" => true]);
    else echo json_encode(["success" => false, "error" => $conn->error]);
    exit;
}

if ($action === 'update_status') {
    $oid = $conn->real_escape_string($data->order_id);
    $st = $conn->real_escape_string($data->status);
    $sql = "UPDATE orders SET status='$st' WHERE id='$oid'";
    if($conn->query($sql)) echo json_encode(["success" => true]);
    else echo json_encode(["success" => false, "error" => $conn->error]);
    exit;
}

$conn->close();
?>
