-- Create view with user initials for Case Detail hours tab
CREATE OR REPLACE VIEW case_detail_hours_view AS
SELECT h.*, CONCAT(LEFT(u.full_name,1), LEFT(split_part(u.full_name,' ',2),1)) AS lawyer_initials
FROM case_hours h
LEFT JOIN users u ON h.user_id = u.id;

-- Register view for sync
INSERT INTO tenant_tables (tenant_id, user_id, table_name, definition)
SELECT NULL, NULL, 'case_detail_hours_view', '{}'
WHERE NOT EXISTS (
    SELECT 1 FROM tenant_tables WHERE table_name = 'case_detail_hours_view'
);

-- Table view for Case Detail hours tab
INSERT INTO table_views (id, table_name, name, columns, sort_by, sort_dir)
SELECT 100, 'case_detail_hours_view', 'Default',
       '["lawyer_initials","title","hours","rate",{"field":"cost","formula":"hours * rate"}]',
       'updatedAt', 'DESC'
WHERE NOT EXISTS (
    SELECT 1 FROM table_views WHERE id = 100
);

-- Update Case Detail modal to use table-view
UPDATE ui_modals SET config = '{"title":"Case Detail","body":[{"type":"tabs","tabs":[{"label":"Hours","elements":[{"type":"button","label":"Add Hour","onClick":"openCaseHourForm"},{"type":"table-view","viewId":100,"recordMap":"formatCaseHourRow"}]},{"label":"Documents","elements":[{"type":"button","label":"Upload Document","onClick":"uploadCaseDocument"},{"type":"table","id":"caseDocsTbl","options":{"tableName":"documents","addButton":false,"showGlobalSearch":false}}]},{"label":"Invoices","elements":[{"type":"button","label":"Create Invoice","onClick":"openCaseInvoiceForm"},{"type":"table","id":"caseInvoicesTbl","options":{"tableName":"invoices","addButton":false,"showGlobalSearch":false}}]},{"label":"Payments","elements":[{"type":"button","label":"Record Payment","onClick":"openCasePaymentForm"},{"type":"table","id":"casePaymentsTbl","options":{"tableName":"payments","addButton":false,"showGlobalSearch":false}}]}]}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'
WHERE name = 'Case Detail';
