<?php
$host = 'localhost:3306';
$dbname = 'gqdcvggs_traffic';
$username = 'gqdcvggs';
$password = 'imaors_management.346980*#@-onlyforcpanel;forchange';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Database connection failed: ' . $e->getMessage()]);
    exit;
}

$action = isset($_GET['action']) ? $_GET['action'] : '';

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

switch ($action) {
    case 'getTrafficLights':
        getTrafficLights($pdo);
        break;
    
    case 'getTrafficLight':
        $id = isset($_GET['id']) ? $_GET['id'] : null;
        getTrafficLight($pdo, $id);
        break;
    
    case 'addTrafficLight':
        addTrafficLight($pdo);
        break;
    
    case 'updateTiming':
        updateTiming($pdo);
        break;
        
    case 'autoDetectLight':
        autoDetectLight($pdo);
        break;
        
    case 'register':
        registerUser($pdo);
        break;
        
    case 'login':
        loginUser($pdo);
        break;
        
    case 'autoLogin':
        autoLogin($pdo);
        break;
        
    case 'logout':
        logoutUser();
        break;
        
    case 'getLightsOnRoute':
        getLightsOnRoute($pdo);
        break;
        
    case 'saveRoute':
        saveRoute($pdo);
        break;
        
    case 'getUserRoutes':
        getUserRoutes($pdo);
        break;
    
    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
}

function getTrafficLights($pdo) {
    try {
        $stmt = $pdo->query("SELECT * FROM traffic_lights WHERE status = 'approved'");
        $lights = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($lights);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Error fetching traffic lights: ' . $e->getMessage()]);
    }
}

function getTrafficLight($pdo, $id) {
    if (!$id) {
        echo json_encode(['success' => false, 'message' => 'ID is required']);
        return;
    }
    
    try {
        $stmt = $pdo->prepare("SELECT * FROM traffic_lights WHERE id = ? AND status = 'approved'");
        $stmt->execute([$id]);
        $light = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($light) {
            echo json_encode($light);
        } else {
            echo json_encode(['success' => false, 'message' => 'Traffic light not found']);
        }
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Error fetching traffic light: ' . $e->getMessage()]);
    }
}

function addTrafficLight($pdo) {
    session_start();
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    
    if (!$data) {
        echo json_encode(['success' => false, 'message' => 'Invalid data format']);
        return;
    }
    
    $required = ['name', 'latitude', 'longitude', 'direction', 'red_duration', 'green_duration'];
    foreach ($required as $field) {
        if (!isset($data[$field])) {
            echo json_encode(['success' => false, 'message' => "$field is required"]);
            return;
        }
    }
    
    try {
        $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
        
        $stmt = $pdo->prepare("INSERT INTO traffic_lights (name, latitude, longitude, direction, red_duration, green_duration, status, user_id) 
                               VALUES (?, ?, ?, ?, ?, ?, 'pending', ?)");
        $stmt->execute([
            $data['name'],
            $data['latitude'],
            $data['longitude'],
            $data['direction'],
            $data['red_duration'],
            $data['green_duration'],
            $userId
        ]);
        
        $id = $pdo->lastInsertId();
        
        $stmt = $pdo->prepare("SELECT * FROM traffic_lights WHERE id = ?");
        $stmt->execute([$id]);
        $light = $stmt->fetch(PDO::FETCH_ASSOC);
        
        echo json_encode(['success' => true, 'light' => $light, 'message' => 'Traffic light added successfully and pending review by Imators team.']);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Error adding traffic light: ' . $e->getMessage()]);
    }
}

function updateTiming($pdo) {
    session_start();
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    
    if (!$data || !isset($data['id']) || !isset($data['duration_type']) || !isset($data['duration'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid data format']);
        return;
    }
    
    $durationType = $data['duration_type'];
    if ($durationType !== 'red' && $durationType !== 'green') {
        echo json_encode(['success' => false, 'message' => 'Invalid duration type']);
        return;
    }
    
    $field = $durationType . '_duration';
    
    try {
        $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
        
        $stmt = $pdo->prepare("UPDATE traffic_lights SET $field = ? WHERE id = ?");
        $stmt->execute([$data['duration'], $data['id']]);
        
        $stmt = $pdo->prepare("SELECT * FROM traffic_lights WHERE id = ?");
        $stmt->execute([$data['id']]);
        $light = $stmt->fetch(PDO::FETCH_ASSOC);
        
        echo json_encode(['success' => true, 'light' => $light]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Error updating traffic light timing: ' . $e->getMessage()]);
    }
}

function autoDetectLight($pdo) {
    session_start();
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    
    if (!$data || !isset($data['latitude']) || !isset($data['longitude']) || !isset($data['duration']) || !isset($data['duration_type'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid data format']);
        return;
    }
    
    try {
        $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
        $latitude = $data['latitude'];
        $longitude = $data['longitude'];
        $duration = $data['duration'];
        $durationType = $data['duration_type'];
        $direction = $data['direction'] ?? 'north';
        
        $stmt = $pdo->prepare("SELECT * FROM traffic_lights 
                              WHERE (
                                 6371 * acos(
                                    cos(radians(?)) * cos(radians(latitude)) * cos(radians(longitude) - radians(?)) + 
                                    sin(radians(?)) * sin(radians(latitude))
                                 )
                              ) < 0.02");
        $stmt->execute([$latitude, $longitude, $latitude]);
        $existingLight = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($existingLight) {
            $field = $durationType . '_duration';
            
            $stmt = $pdo->prepare("UPDATE traffic_lights SET $field = ? WHERE id = ?");
            $stmt->execute([$duration, $existingLight['id']]);
            
            $stmt = $pdo->prepare("SELECT * FROM traffic_lights WHERE id = ?");
            $stmt->execute([$existingLight['id']]);
            $light = $stmt->fetch(PDO::FETCH_ASSOC);
            
            echo json_encode(['success' => true, 'light' => $light, 'message' => 'Traffic light timing updated']);
        } else {
            $name = "Auto-detected light";
            $redDuration = ($durationType === 'red') ? $duration : 60;
            $greenDuration = ($durationType === 'green') ? $duration : 30;
            
            $stmt = $pdo->prepare("INSERT INTO traffic_lights (name, latitude, longitude, direction, red_duration, 
                                  green_duration, status, user_id) 
                                  VALUES (?, ?, ?, ?, ?, ?, 'pending', ?)");
            $stmt->execute([
                $name,
                $latitude,
                $longitude,
                $direction,
                $redDuration,
                $greenDuration,
                $userId
            ]);
            
            $id = $pdo->lastInsertId();
            
            $stmt = $pdo->prepare("SELECT * FROM traffic_lights WHERE id = ?");
            $stmt->execute([$id]);
            $light = $stmt->fetch(PDO::FETCH_ASSOC);
            
            echo json_encode(['success' => true, 'light' => $light, 'message' => 'New traffic light auto-detected']);
        }
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Error processing auto-detected light: ' . $e->getMessage()]);
    }
}

function registerUser($pdo) {
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    
    if (!$data || !isset($data['username']) || !isset($data['email']) || !isset($data['password'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid data format']);
        return;
    }
    
    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$data['email']]);
        if ($stmt->fetch()) {
            echo json_encode(['success' => false, 'message' => 'Email already registered']);
            return;
        }
        
        $hashedPassword = password_hash($data['password'], PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("INSERT INTO users (name, email, password, created_at) VALUES (?, ?, ?, NOW())");
        $stmt->execute([$data['username'], $data['email'], $hashedPassword]);
        
        $userId = $pdo->lastInsertId();
        
        session_start();
        $_SESSION['user_id'] = $userId;
        $_SESSION['username'] = $data['username'];
        $_SESSION['email'] = $data['email'];
        
        if (isset($data['remember']) && $data['remember']) {
            $expiry = time() + (86400 * 30);
            setcookie('user_id', $userId, $expiry, '/');
            setcookie('username', $data['username'], $expiry, '/');
        }
        
        echo json_encode(['success' => true, 'message' => 'Registration successful', 'user' => [
            'id' => $userId,
            'username' => $data['username'],
            'email' => $data['email']
        ]]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Error registering user: ' . $e->getMessage()]);
    }
}

function loginUser($pdo) {
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    
    if (!$data || !isset($data['email']) || !isset($data['password'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid data format']);
        return;
    }
    
    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$data['email']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user || !password_verify($data['password'], $user['password'])) {
            echo json_encode(['success' => false, 'message' => 'Invalid email or password']);
            return;
        }
        
        $stmt = $pdo->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
        $stmt->execute([$user['id']]);
        
        session_start();
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['name'];
        $_SESSION['email'] = $user['email'];
        
        if (isset($data['remember']) && $data['remember']) {
            $expiry = time() + (86400 * 30);
            setcookie('user_id', $user['id'], $expiry, '/');
            setcookie('username', $user['name'], $expiry, '/');
        }
        
        echo json_encode(['success' => true, 'message' => 'Login successful', 'user' => [
            'id' => $user['id'],
            'username' => $user['name'],
            'email' => $user['email']
        ]]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Error logging in: ' . $e->getMessage()]);
    }
}

function autoLogin($pdo) {
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    
    if (!$data || !isset($data['user_id']) || !isset($data['username'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid auto-login data']);
        return;
    }
    
    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$data['user_id']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            echo json_encode(['success' => false, 'message' => 'User not found']);
            return;
        }
        
        session_start();
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['name'];
        $_SESSION['email'] = $user['email'];
        
        echo json_encode(['success' => true, 'message' => 'Auto-login successful', 'user' => [
            'id' => $user['id'],
            'username' => $user['name'],
            'email' => $user['email']
        ]]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Error with auto-login: ' . $e->getMessage()]);
    }
}

function logoutUser() {
    session_start();
    session_destroy();
    
    setcookie('user_id', '', time() - 3600, '/');
    setcookie('username', '', time() - 3600, '/');
    
    echo json_encode(['success' => true, 'message' => 'Logout successful']);
}

function getLightsOnRoute($pdo) {
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    
    if (!$data || !isset($data['coordinates']) || !is_array($data['coordinates'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid data format']);
        return;
    }
    
    try {
        $lights = [];
        $routePoints = $data['coordinates'];
        
        foreach ($routePoints as $point) {
            if (!isset($point[0]) || !isset($point[1])) {
                continue;
            }
            
            $longitude = $point[0];
            $latitude = $point[1];
            
            $stmt = $pdo->prepare("SELECT * FROM traffic_lights 
                                  WHERE status = 'approved' AND (
                                     6371 * acos(
                                        cos(radians(?)) * cos(radians(latitude)) * cos(radians(longitude) - radians(?)) + 
                                        sin(radians(?)) * sin(radians(latitude))
                                     )
                                  ) < 0.05");
            $stmt->execute([$latitude, $longitude, $latitude]);
            $nearbyLights = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($nearbyLights as $light) {
                $exists = false;
                foreach ($lights as $existingLight) {
                    if ($existingLight['id'] == $light['id']) {
                        $exists = true;
                        break;
                    }
                }
                
                if (!$exists) {
                    $lights[] = $light;
                }
            }
        }
        
        echo json_encode(['success' => true, 'lights' => $lights]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Error fetching lights on route: ' . $e->getMessage()]);
    }
}

function saveRoute($pdo) {
    session_start();
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    
    if (!$data || !isset($data['name']) || !isset($data['start_point']) || !isset($data['end_point']) || !isset($data['coordinates'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid data format']);
        return;
    }
    
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'User must be logged in to save routes']);
        return;
    }
    
    try {
        $userId = $_SESSION['user_id'];
        $routeData = json_encode([
            'start_point' => $data['start_point'],
            'end_point' => $data['end_point'],
            'coordinates' => $data['coordinates'],
            'distance' => $data['distance'] ?? null,
            'duration' => $data['duration'] ?? null,
            'travel_mode' => $data['travel_mode'] ?? 'driving'
        ]);
        
        $stmt = $pdo->prepare("INSERT INTO saved_routes (user_id, name, route_data, created_at) VALUES (?, ?, ?, NOW())");
        $stmt->execute([$userId, $data['name'], $routeData]);
        
        $routeId = $pdo->lastInsertId();
        
        echo json_encode(['success' => true, 'message' => 'Route saved successfully', 'route_id' => $routeId]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Error saving route: ' . $e->getMessage()]);
    }
}

function getUserRoutes($pdo) {
    session_start();
    
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'User must be logged in to view saved routes']);
        return;
    }
    
    try {
        $userId = $_SESSION['user_id'];
        
        $stmt = $pdo->prepare("SELECT * FROM saved_routes WHERE user_id = ? ORDER BY created_at DESC");
        $stmt->execute([$userId]);
        $routes = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($routes as &$route) {
            $route['route_data'] = json_decode($route['route_data'], true);
        }
        
        echo json_encode(['success' => true, 'routes' => $routes]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Error fetching routes: ' . $e->getMessage()]);
    }
}
?>