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

// Auto-migrate schema to support minimum working hours
try {
    $hasCol = fetch("SHOW COLUMNS FROM shifts LIKE 'minimum_working_hours'");
    if (!$hasCol) {
        query("ALTER TABLE shifts ADD COLUMN minimum_working_hours DECIMAL(4,2) NOT NULL DEFAULT 0.00 AFTER working_hours");
    }
} catch (Exception $e) {
    // Ignore database schema checking issues
}

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

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

$data = json_decode(file_get_contents('php://input'), true);
$action = $_POST['action'] ?? $data['action'] ?? $_GET['action'] ?? '';
$company_id = $_SESSION['company_id'];

switch ($action) {
    case 'list':
        try {
            $shifts = fetchAll("
                SELECT s.*, COUNT(e.id) as employee_count 
                FROM shifts s 
                LEFT JOIN employees e ON s.id = e.shift_id 
                WHERE s.company_id = ? 
                GROUP BY s.id 
                ORDER BY s.created_at DESC
            ", [$company_id]);
            
            // Format times for cleaner UI presentation
            foreach ($shifts as &$shift) {
                $shift['start_time_formatted'] = date("g:i A", strtotime($shift['start_time']));
                $shift['end_time_formatted'] = date("g:i A", strtotime($shift['end_time']));
            }
            
            echo json_encode(['success' => true, 'data' => $shifts]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
        break;

    case 'save':
        $shift = $data['shift'] ?? [];
        $id = $shift['id'] ?? '';
        $name = trim($shift['name'] ?? '');
        $start_time = trim($shift['start_time'] ?? '');
        $end_time = trim($shift['end_time'] ?? '');
        $minimum_working_hours = floatval($shift['minimum_working_hours'] ?? 0.00);

        if (empty($name) || empty($start_time) || empty($end_time)) {
            echo json_encode(['success' => false, 'message' => 'All fields (Name, Start Time, End Time) are required.']);
            exit;
        }

        try {
            // Auto calculate working hours (including midnight crossing)
            $start = new DateTime($start_time);
            $end = new DateTime($end_time);
            if ($end < $start) {
                $end->modify('+1 day');
            }
            $diff = $start->diff($end);
            $working_hours = $diff->h + ($diff->i / 60);

            if ($id) {
                // Update
                query("
                    UPDATE shifts 
                    SET name = ?, start_time = ?, end_time = ?, working_hours = ?, minimum_working_hours = ? 
                    WHERE id = ? AND company_id = ?
                ", [$name, $start_time, $end_time, $working_hours, $minimum_working_hours, $id, $company_id]);
                echo json_encode(['success' => true, 'message' => 'Shift updated successfully.']);
            } else {
                // Insert
                query("
                    INSERT INTO shifts (company_id, name, start_time, end_time, working_hours, minimum_working_hours) 
                    VALUES (?, ?, ?, ?, ?, ?)
                ", [$company_id, $name, $start_time, $end_time, $working_hours, $minimum_working_hours]);
                echo json_encode(['success' => true, 'message' => 'Shift created successfully.']);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
        }
        break;

    case 'delete':
        $id = $data['id'] ?? '';
        if (!$id) {
            echo json_encode(['success' => false, 'message' => 'Shift ID is required.']);
            exit;
        }
        try {
            query("DELETE FROM shifts WHERE id = ? AND company_id = ?", [$id, $company_id]);
            echo json_encode(['success' => true, 'message' => 'Shift deleted successfully.']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Delete failed: ' . $e->getMessage()]);
        }
        break;

    case 'search_employees':
        $shift_id = intval($_GET['shift_id'] ?? 0);
        $search = trim($_GET['query'] ?? '');
        $likeQuery = "%$search%";

        try {
            // Retrieve active employees who are NOT already assigned to this specific shift
            $employees = fetchAll("
                SELECT e.id, e.name, e.employee_code, e.profile_picture, r.name as role_name 
                FROM employees e 
                LEFT JOIN roles r ON e.role_id = r.id 
                WHERE e.company_id = ? 
                  AND (e.shift_id != ? OR e.shift_id IS NULL)
                  AND (e.name LIKE ? OR e.employee_code LIKE ?)
                  AND e.is_active = 1
                ORDER BY e.name ASC
                LIMIT 20
            ", [$company_id, $shift_id, $likeQuery, $likeQuery]);

            echo json_encode(['success' => true, 'data' => $employees]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Search failed: ' . $e->getMessage()]);
        }
        break;

    case 'list_tagged_employees':
        $shift_id = intval($_GET['shift_id'] ?? 0);
        try {
            $employees = fetchAll("
                SELECT e.id, e.name, e.employee_code, e.profile_picture, r.name as role_name 
                FROM employees e 
                LEFT JOIN roles r ON e.role_id = r.id 
                WHERE e.company_id = ? AND e.shift_id = ?
                ORDER BY e.name ASC
            ", [$company_id, $shift_id]);
            echo json_encode(['success' => true, 'data' => $employees]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Failed to load tagged employees: ' . $e->getMessage()]);
        }
        break;

    case 'tag_employees':
        $shift_id = intval($data['shift_id'] ?? 0);
        $employee_ids = $data['employee_ids'] ?? [];

        if (!$shift_id || empty($employee_ids)) {
            echo json_encode(['success' => false, 'message' => 'Invalid parameters. Selected employees required.']);
            exit;
        }

        try {
            $placeholders = implode(',', array_fill(0, count($employee_ids), '?'));
            $params = array_merge([$shift_id], $employee_ids, [$company_id]);
            
            query("
                UPDATE employees 
                SET shift_id = ? 
                WHERE id IN ($placeholders) AND company_id = ?
            ", $params);

            echo json_encode(['success' => true, 'message' => 'Employees assigned to shift successfully.']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Bulk tagging failed: ' . $e->getMessage()]);
        }
        break;

    case 'untag_employee':
        $employee_id = intval($data['employee_id'] ?? 0);
        if (!$employee_id) {
            echo json_encode(['success' => false, 'message' => 'Employee ID is required.']);
            exit;
        }

        try {
            query("
                UPDATE employees 
                SET shift_id = NULL 
                WHERE id = ? AND company_id = ?
            ", [$employee_id, $company_id]);
            echo json_encode(['success' => true, 'message' => 'Employee removed from shift successfully.']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Untag failed: ' . $e->getMessage()]);
        }
        break;

    case 'save_assignments':
        $shift_id = intval($data['shift_id'] ?? 0);
        $employee_ids = $data['employee_ids'] ?? [];

        if (!$shift_id) {
            echo json_encode(['success' => false, 'message' => 'Invalid shift ID.']);
            exit;
        }

        try {
            global $pdo;
            $pdo->beginTransaction();

            // 1. Untag all employees currently assigned to this shift in this company
            query("
                UPDATE employees 
                SET shift_id = NULL 
                WHERE shift_id = ? AND company_id = ?
            ", [$shift_id, $company_id]);

            // 2. Tag the new set of employees
            if (!empty($employee_ids)) {
                $placeholders = implode(',', array_fill(0, count($employee_ids), '?'));
                $params = array_merge([$shift_id], $employee_ids, [$company_id]);
                
                query("
                    UPDATE employees 
                    SET shift_id = ? 
                    WHERE id IN ($placeholders) AND company_id = ?
                ", $params);
            }

            $pdo->commit();
            echo json_encode(['success' => true, 'message' => 'Shift assignments updated successfully.']);
        } catch (Exception $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            echo json_encode(['success' => false, 'message' => 'Failed to save assignments: ' . $e->getMessage()]);
        }
        break;

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