<?php
session_start();

header('Content-Type: application/json');

if (!isset($_SESSION['csr_id'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access.'
    ]);
    exit;
}

require_once '../../config/database.php';
require_once '../../includes/app_helpers.php';

try {
    $db = (new Database())->getConnection();
    ensureAddressAndCallQueueTables($db);

    $csrId = (int)$_SESSION['csr_id'];
    $callId = (int)($_POST['call_id'] ?? 0);

    if ($callId <= 0) {
        throw new Exception('Invalid call record.');
    }

    $scope = getCsrRequestScope($db, $csrId);
    $isManager = !empty($scope['is_manager']);

    $teamIds = [];
    $memberIds = [];

    if ($isManager) {
        $teamIds = array_values(array_unique(array_map('intval', $scope['team_ids'] ?? [])));
        $memberIds = array_values(array_unique(array_map('intval', $scope['member_ids'] ?? [])));
    }

    $whereAccess = [];
    $params = [
        ':call_id' => $callId,
        ':csr_accepted' => $csrId,
        ':csr_assigned' => $csrId
    ];

    $whereAccess[] = 'cr.accepted_by = :csr_accepted';
    $whereAccess[] = 'cr.assigned_csr_id = :csr_assigned';

    if ($isManager && !empty($memberIds)) {
        $acceptedMemberPlaceholders = [];
        $assignedMemberPlaceholders = [];

        foreach ($memberIds as $index => $memberId) {
            $acceptedKey = ':accepted_member_' . $index;
            $assignedKey = ':assigned_member_' . $index;

            $acceptedMemberPlaceholders[] = $acceptedKey;
            $assignedMemberPlaceholders[] = $assignedKey;

            $params[$acceptedKey] = $memberId;
            $params[$assignedKey] = $memberId;
        }

        $whereAccess[] = 'cr.accepted_by IN (' . implode(',', $acceptedMemberPlaceholders) . ')';
        $whereAccess[] = 'cr.assigned_csr_id IN (' . implode(',', $assignedMemberPlaceholders) . ')';
    }

    if ($isManager && !empty($teamIds)) {
        $teamPlaceholders = [];

        foreach ($teamIds as $index => $teamId) {
            $teamKey = ':team_' . $index;
            $teamPlaceholders[] = $teamKey;
            $params[$teamKey] = $teamId;
        }

        $whereAccess[] = 'cr.team_id IN (' . implode(',', $teamPlaceholders) . ')';
    }

    $accessSql = "
        SELECT 
            cr.id,
            cr.recording_path,
            cr.status
        FROM call_requests cr
        WHERE cr.id = :call_id
          AND cr.status IN ('completed', 'missed', 'cancelled')
          AND (
                " . implode(' OR ', $whereAccess) . "
          )
        LIMIT 1
    ";

    $stmt = $db->prepare($accessSql);

    foreach ($params as $key => $value) {
        $stmt->bindValue($key, (int)$value, PDO::PARAM_INT);
    }

    $stmt->execute();
    $call = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$call) {
        throw new Exception('Call record not found or you do not have permission to delete it.');
    }

    $recordingPath = trim($call['recording_path'] ?? '');

    $db->beginTransaction();

    $deleteStmt = $db->prepare("
        DELETE FROM call_requests
        WHERE id = :delete_call_id
        LIMIT 1
    ");

    $deleteStmt->bindValue(':delete_call_id', $callId, PDO::PARAM_INT);
    $deleteStmt->execute();

    $db->commit();

    if ($recordingPath !== '') {
        $fullPath = realpath(__DIR__ . '/../../' . $recordingPath);
        $uploadsPath = realpath(__DIR__ . '/../../uploads');

        if (
            $fullPath &&
            $uploadsPath &&
            strpos($fullPath, $uploadsPath) === 0 &&
            file_exists($fullPath)
        ) {
            @unlink($fullPath);
        }
    }

    echo json_encode([
        'success' => true,
        'message' => 'Call record deleted successfully.'
    ]);
} catch (Exception $e) {
    if (isset($db) && $db->inTransaction()) {
        $db->rollBack();
    }

    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}