-- Migration: Update timetracking views to exclude billed entries
-- Ensures that time entries with billed_via_thehub_id are not shown in pending counts

-- Drop and recreate approval stats view to exclude billed entries
DROP VIEW IF EXISTS tmodule_approval_stats CASCADE;
CREATE VIEW tmodule_approval_stats AS
SELECT 
    c.id AS customer_id,
    c.name AS customer_name,
    c.vtiger_id AS customer_vtiger_id,
    c.uses_time_card AS uses_time_card,
    COUNT(t.id) FILTER (WHERE t.billable = true AND t.billed_via_thehub_id IS NULL) AS total_entries,
    COUNT(t.id) FILTER (WHERE t.billable = true AND t.status = 'pending' AND t.billed_via_thehub_id IS NULL) AS pending_count,
    COUNT(t.id) FILTER (WHERE t.billable = true AND t.status = 'approved' AND t.billed_via_thehub_id IS NULL) AS approved_count,
    COUNT(t.id) FILTER (WHERE t.billable = true AND t.status = 'rejected') AS rejected_count,
    COUNT(t.id) FILTER (WHERE t.billable = true AND t.status = 'billed') AS billed_count,
    SUM(t.original_hours) FILTER (WHERE t.billable = true AND t.billed_via_thehub_id IS NULL) AS total_original_hours,
    SUM(t.approved_hours) FILTER (WHERE t.billable = true AND t.status = 'approved' AND t.billed_via_thehub_id IS NULL) AS total_approved_hours,
    MAX(t.worked_date) FILTER (WHERE t.billable = true AND t.billed_via_thehub_id IS NULL) AS latest_work_date,
    MAX(t.last_synced_at) FILTER (WHERE t.billable = true AND t.billed_via_thehub_id IS NULL) AS last_sync
FROM tmodule_customers c
LEFT JOIN tmodule_times t ON c.id = t.customer_id
GROUP BY c.id, c.name, c.vtiger_id, c.uses_time_card;

-- Drop and recreate next pending view to exclude billed entries
DROP VIEW IF EXISTS tmodule_next_pending CASCADE;
CREATE VIEW tmodule_next_pending AS
SELECT 
    t.*,
    COALESCE(c.vtiger_data->>'case_no', c.title)::VARCHAR(500) AS case_title,
    c.status AS case_status,
    c.vtiger_id AS case_vtiger_id,
    cust.name AS customer_name,
    cust.hourly_rate AS customer_rate
FROM tmodule_times t
JOIN tmodule_cases c ON t.case_id = c.id
JOIN tmodule_customers cust ON t.customer_id = cust.id
WHERE t.status = 'pending' 
  AND t.billable = true
  AND t.billed_via_thehub_id IS NULL
ORDER BY cust.name, c.title, t.worked_date;
