<?php
require_once '../includes/auth.php';
require_once '../includes/db.php';

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

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Optimization: Release session lock early to prevent blocking other concurrent requests
session_write_close();

$data = json_decode(file_get_contents('php://input'), true);
// Determine action for both JSON and FormData
$action = $_POST['action'] ?? $data['action'] ?? '';

switch ($action) {
    case 'update-status':
        $id = $_POST['id'] ?? $data['id'];
        $status = $_POST['status'] ?? $data['status'];
        query("UPDATE tasks SET status = ? WHERE id = ?", [$status, $id]);
        echo json_encode(['success' => true, 'message' => "Task status updated to $status"]);
        break;

    case 'get-log-history':
        $taskId = $data['task_id'] ?? $_GET['task_id'];
        $logs = fetchAll("SELECT tl.*, ts.name as status_name 
                         FROM task_time_logs tl 
                         JOIN task_statuses ts ON tl.task_status_id = ts.id 
                         WHERE tl.task_id = ? 
                         ORDER BY tl.log_date DESC, tl.created_at DESC", [$taskId]);
        
        if (!empty($logs)) {
            $logIds = array_column($logs, 'id');
            $placeholders = implode(',', array_fill(0, count($logIds), '?'));
            $allAttachments = fetchAll("SELECT * FROM task_log_attachments WHERE log_id IN ($placeholders)", $logIds);
            
            foreach ($logs as &$log) {
                $log['attachments'] = array_values(array_filter($allAttachments, function($a) use ($log) {
                    return $a['log_id'] == $log['id'];
                }));
            }
        }
        echo json_encode(['success' => true, 'data' => $logs]);
        break;

    case 'delete-log':
        $logId = $data['log_id'];
        $log = fetch("SELECT log_date FROM task_time_logs WHERE id = ?", [$logId]);
        
        if ($log && $log['log_date'] === date('Y-m-d')) {
            // Delete attachments from disk
            $attachments = fetchAll("SELECT file_path FROM task_log_attachments WHERE log_id = ?", [$logId]);
            foreach ($attachments as $a) {
                if (file_exists('../' . $a['file_path'])) unlink('../' . $a['file_path']);
            }
            query("DELETE FROM task_log_attachments WHERE log_id = ?", [$logId]);
            query("DELETE FROM task_time_logs WHERE id = ?", [$logId]);
            echo json_encode(['success' => true, 'message' => 'Log deleted successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'You can only delete today\'s logs']);
        }
        break;

    case 'log-effort':
        $taskId = $_POST['task_id'];
        $statusId = $_POST['task_status_id'];
        $comments = $_POST['comments'] ?? '';
        $hours = $_POST['hours_spent'] ?? 0;
        $logDate = date('Y-m-d');
        
        try {
            // Optimization: We'll use a subquery in the UPDATE statement later 
            // to avoid this initial fetch roundtrip.

            // 2. Handle Multiple Attachments (Move outside transaction to avoid disk I/O blocking)
            $attachmentsToInsert = [];
            if (!empty($_FILES['attachments']['name'][0])) {
                $uploadDir = '../uploads/tasks/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
                
                foreach ($_FILES['attachments']['name'] as $key => $name) {
                    if ($_FILES['attachments']['error'][$key] === UPLOAD_ERR_OK) {
                        $ext = pathinfo($name, PATHINFO_EXTENSION);
                        // Using a temporary unique name before we get the Log ID
                        $tempName = time() . '_tmp_' . $key . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
                        $targetFile = $uploadDir . $tempName;
                        
                        if (move_uploaded_file($_FILES['attachments']['tmp_name'][$key], $targetFile)) {
                            $attachmentsToInsert[] = [
                                'file_path' => 'uploads/tasks/' . $tempName,
                                'file_name' => $name
                            ];
                        }
                    }
                }
            }

            // 3. Start Database Transaction (Focus only on DB writes)
           $pdo->beginTransaction();
            
            // Update Task Status (Optimization: Subquery combined to reduce roundtrips)
            query("UPDATE tasks SET status = (SELECT name FROM task_statuses WHERE id = ?), updated_at = NOW() WHERE id = ?", [$statusId, $taskId]);
            
            // Insert Log
            query("INSERT INTO task_time_logs (task_id, user_id, log_date, hours_spent, task_status_id, comments, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())", [
                $taskId, $_SESSION['user_id'], $logDate, $hours, $statusId, $comments
            ]);
            $logId = $pdo->lastInsertId();
            
            // Insert Attachment Records (Batching)
            if (!empty($attachmentsToInsert)) {
                $sql = "INSERT INTO task_log_attachments (log_id, file_path, file_name) VALUES ";
                $values = [];
                $params = [];
                foreach ($attachmentsToInsert as $a) {
                    $values[] = "(?, ?, ?)";
                    $params[] = $logId;
                    $params[] = $a['file_path'];
                    $params[] = $a['file_name'];
                }
                query($sql . implode(', ', $values), $params);
            }
            
            $pdo->commit();
            echo json_encode(['success' => true, 'message' => 'Effort logged successfully']);
        } catch (Exception $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}
