<?php
session_start();
require '../db/config.php';
$db = db();

if (!isset($_SESSION['user_id'])) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$userId = $_SESSION['user_id'];
$data = json_decode(file_get_contents('php://input'), true);

if (!$data || !isset($data['opId']) || !isset($data['action'])) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => 'Invalid data']);
    exit;
}

$opId = $data['opId'];
$action = $data['action'];
$reason = $data['reason'] ?? null;

try {
    $db->beginTransaction();

    // Fetch current op state
    $stmt = $db->prepare("SELECT * FROM operations WHERE id = ?");
    $stmt->execute([$opId]);
    $op = $stmt->fetch();

    if (!$op) {
        throw new Exception("Operation not found");
    }

    $eventType = '';
    $statusUpdate = '';
    $now = date('Y-m-d H:i:s');

    switch ($action) {
        case 'start':
            $statusUpdate = "status = 'in_progress', assigned_worker_id = $userId, start_time = IFNULL(start_time, '$now')";
            $eventType = 'start';
            // If it was stalled, event type is 'resume'
            if ($op['status'] === 'stalled') {
                $eventType = 'resume';
            }
            break;
        
        case 'stall':
            $statusUpdate = "status = 'stalled', stall_reason = " . $db->quote($reason);
            $eventType = 'stalled';
            break;
            
        case 'done':
            $statusUpdate = "status = 'completed', end_time = '$now'";
            $eventType = 'completed';
            break;
        
        default:
            throw new Exception("Invalid action");
    }

    // Update operation
    $db->exec("UPDATE operations SET $statusUpdate WHERE id = $opId");

    // Log time study event
    $stmt = $db->prepare("INSERT INTO time_study_events (operation_id, user_id, event_type, reason) VALUES (?, ?, ?, ?)");
    $stmt->execute([$opId, $userId, $eventType, $reason]);

    // Post-completion logic (if done)
    if ($action === 'done') {
        // Check if all operations for this component are done
        $compId = $op['component_id'];
        $pendingOps = $db->prepare("SELECT COUNT(*) FROM operations WHERE component_id = ? AND status != 'completed'");
        $pendingOps->execute([$compId]);
        if ($pendingOps->fetchColumn() == 0) {
            // Component is done
            $db->exec("UPDATE components SET status = 'completed' WHERE id = $compId");

            // Check if all components for this job are done
            $stmt = $db->prepare("SELECT job_id FROM components WHERE id = ?");
            $stmt->execute([$compId]);
            $jobId = $stmt->fetchColumn();

            $pendingComps = $db->prepare("SELECT COUNT(*) FROM components WHERE job_id = ? AND status != 'completed'");
            $pendingComps->execute([$jobId]);
            if ($pendingComps->fetchColumn() == 0) {
                // Job is done
                $db->exec("UPDATE jobs SET status = 'completed' WHERE id = $jobId");
            } else {
                // Job is in_progress if not already
                $db->exec("UPDATE jobs SET status = 'in_progress' WHERE id = $jobId");
            }
        } else {
            // Component is in_progress if not already
            $db->exec("UPDATE components SET status = 'in_progress' WHERE id = $compId");
            
            // Job is in_progress
            $stmt = $db->prepare("SELECT job_id FROM components WHERE id = ?");
            $stmt->execute([$compId]);
            $jobId = $stmt->fetchColumn();
            $db->exec("UPDATE jobs SET status = 'in_progress' WHERE id = $jobId");
        }
    }

    $db->commit();
    echo json_encode(['success' => true]);

} catch (Exception $e) {
    $db->rollBack();
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
