<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_user.php';

apply_cors();
$authUser = require_user();
$pdo = getDbConnection();
$method = $_SERVER['REQUEST_METHOD'];

// POST   /call_logs.php          -> record a new auto-reply event (called by native services)
// GET    /call_logs.php          -> list (filter by status/type, paginate)
// GET    /call_logs.php?id=5     -> single detail
// DELETE /call_logs.php          -> clear all logs for this user
// DELETE /call_logs.php?id=5     -> delete one entry

if ($method === 'POST') {
    $input = get_json_input();
    require_fields($input, ['phone_number', 'call_type', 'status', 'channel_used']);

    $stmt = $pdo->prepare(
        'INSERT INTO call_logs (user_email, phone_number, caller_name, call_type, status, channel_used,
                                 template_title, message_content, event_timestamp)
         VALUES (:email, :phone, :caller, :type, :status, :channel, :template, :message, :ts)'
    );
    $stmt->execute([
        ':email'    => $authUser['email'],
        ':phone'    => clean_str($input['phone_number']),
        ':caller'   => clean_str($input['caller_name'] ?? ''),
        ':type'     => clean_str($input['call_type']),
        ':status'   => clean_str($input['status']),
        ':channel'  => clean_str($input['channel_used']),
        ':template' => clean_str($input['template_title'] ?? ''),
        ':message'  => clean_str($input['message_content'] ?? ''),
        ':ts'       => (int) ($input['event_timestamp'] ?? (time() * 1000)),
    ]);

    send_success(['log_id' => (int) $pdo->lastInsertId()], 'Logged.', 201);
}

if ($method === 'GET' && isset($_GET['id'])) {
    $stmt = $pdo->prepare('SELECT * FROM call_logs WHERE id = :id AND user_email = :email');
    $stmt->execute([':id' => (int) $_GET['id'], ':email' => $authUser['email']]);
    $row = $stmt->fetch();
    if (!$row) send_error('Log not found.', 404);
    send_success(['log' => $row]);
}

if ($method === 'GET') {
    [$page, $perPage, $offset] = paginate_params();
    $status = clean_str($_GET['status'] ?? '');
    $type = clean_str($_GET['call_type'] ?? '');
    $search = clean_str($_GET['search'] ?? '');

    $where = ['user_email = :email'];
    $params = [':email' => $authUser['email']];
    if ($status !== '') { $where[] = 'status = :status'; $params[':status'] = $status; }
    if ($type !== '') { $where[] = 'call_type = :type'; $params[':type'] = $type; }
    if ($search !== '') { $where[] = '(phone_number LIKE :search OR caller_name LIKE :search2)'; $params[':search'] = "%$search%"; $params[':search2'] = "%$search%"; }
    $whereSql = implode(' AND ', $where);

    $count = $pdo->prepare("SELECT COUNT(*) FROM call_logs WHERE $whereSql");
    $count->execute($params);
    $total = (int) $count->fetchColumn();

    $stmt = $pdo->prepare("SELECT * FROM call_logs WHERE $whereSql ORDER BY created_at DESC LIMIT :limit OFFSET :offset");
    foreach ($params as $k => $v) $stmt->bindValue($k, $v);
    $stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();

    send_success([
        'logs' => $stmt->fetchAll(),
        'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
    ]);
}

if ($method === 'DELETE' && isset($_GET['id'])) {
    $stmt = $pdo->prepare('DELETE FROM call_logs WHERE id = :id AND user_email = :email');
    $stmt->execute([':id' => (int) $_GET['id'], ':email' => $authUser['email']]);
    send_success(null, 'Log deleted.');
}

if ($method === 'DELETE') {
    $stmt = $pdo->prepare('DELETE FROM call_logs WHERE user_email = :email');
    $stmt->execute([':email' => $authUser['email']]);
    send_success(null, 'All logs cleared.');
}

send_error('Invalid request.', 400);
