<?php
/**
 * Manager Profile & Settings API
 * Handles profile updates, password changes, and account settings
 */

// Start session first
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

// Enable error logging for debugging
error_log('Manager API - Session ID: ' . session_id() . ', Manager ID: ' . ($_SESSION['manager_id'] ?? 'NOT SET'));

// Check authentication
if (!isset($_SESSION['manager_id'])) {
    error_log('Manager API - Unauthorized: Session not set');
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access. Please log in again.']);
    exit;
}

// Include config and verify connection
require_once 'config.php';

// Verify database connection
if (!$conn) {
    error_log('Manager API - Database connection failed: ' . mysqli_connect_error());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

if ($conn->connect_error) {
    error_log('Manager API - Connection error: ' . $conn->connect_error);
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->connect_error]);
    exit;
}

$manager_id = $_SESSION['manager_id'];
$action = $_GET['action'] ?? '';

error_log('Manager API - Action: ' . $action . ', Manager ID: ' . $manager_id);

// Get current manager details
function getManagerDetails($conn, $manager_id) {
    $stmt = $conn->prepare("SELECT id, name, email, phone, employee_id, shift_type, status FROM managers WHERE id = ?");
    $stmt->bind_param("i", $manager_id);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

// Update profile information (name, phone, shift_type)
if ($action === 'updateProfile') {
    $data = json_decode(file_get_contents('php://input'), true);
    
    $name = trim($data['name'] ?? '');
    $phone = trim($data['phone'] ?? '');
    $shift_type = trim($data['shift_type'] ?? 'day');
    
    // Validation
    if (empty($name)) {
        sendResponse(false, 'Full name is required');
        exit;
    }
    
    if (!in_array($shift_type, ['day', 'evening', 'night'])) {
        sendResponse(false, 'Invalid shift type');
        exit;
    }
    
    try {
        $stmt = $conn->prepare("UPDATE managers SET name = ?, phone = ?, shift_type = ?, updated_at = NOW() WHERE id = ?");
        $stmt->bind_param("sssi", $name, $phone, $shift_type, $manager_id);
        
        if ($stmt->execute()) {
            $manager = getManagerDetails($conn, $manager_id);
            sendResponse(true, 'Profile updated successfully', $manager);
        } else {
            sendResponse(false, 'Failed to update profile: ' . $stmt->error);
        }
    } catch (Exception $e) {
        sendResponse(false, 'Error: ' . $e->getMessage());
    }
}

// Change password
elseif ($action === 'changePassword') {
    error_log('Manager API - changePassword action started');
    
    $input = file_get_contents('php://input');
    error_log('Manager API - Raw input: ' . $input);
    
    $data = json_decode($input, true);
    error_log('Manager API - Decoded data: ' . json_encode($data));
    
    if (!$data) {
        error_log('Manager API - Failed to decode JSON');
        sendResponse(false, 'Invalid JSON data');
        exit;
    }
    
    $currentPassword = $data['currentPassword'] ?? '';
    $newPassword = $data['newPassword'] ?? '';
    $confirmPassword = $data['confirmPassword'] ?? '';
    
    error_log('Manager API - Passwords received - Current: ' . (strlen($currentPassword) > 0 ? 'YES' : 'NO') . ', New: ' . (strlen($newPassword) > 0 ? 'YES' : 'NO') . ', Confirm: ' . (strlen($confirmPassword) > 0 ? 'YES' : 'NO'));
    
    // Validation
    if (empty($currentPassword) || empty($newPassword) || empty($confirmPassword)) {
        error_log('Manager API - Empty password fields');
        sendResponse(false, 'All password fields are required');
        exit;
    }
    
    if (strlen($newPassword) < 8) {
        error_log('Manager API - New password too short: ' . strlen($newPassword));
        sendResponse(false, 'New password must be at least 8 characters');
        exit;
    }
    
    if ($newPassword !== $confirmPassword) {
        error_log('Manager API - Passwords do not match');
        sendResponse(false, 'New passwords do not match');
        exit;
    }
    
    try {
        // Verify current password
        error_log('Manager API - Fetching manager password record for ID: ' . $manager_id);
        
        $stmt = $conn->prepare("SELECT password FROM managers WHERE id = ?");
        if (!$stmt) {
            error_log('Manager API - Prepare failed: ' . $conn->error);
            sendResponse(false, 'Database error: ' . $conn->error);
            exit;
        }
        
        $stmt->bind_param("i", $manager_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            error_log('Manager API - Manager not found with ID: ' . $manager_id);
            sendResponse(false, 'Manager not found');
            exit;
        }
        
        $row = $result->fetch_assoc();
        error_log('Manager API - Manager record found, password hash exists: ' . (strlen($row['password']) > 0 ? 'YES' : 'NO'));
        
        // Verify current password
        $passwordValid = password_verify($currentPassword, $row['password']);
        error_log('Manager API - Password verification result: ' . ($passwordValid ? 'VALID' : 'INVALID'));
        
        if (!$passwordValid) {
            error_log('Manager API - Current password verification failed');
            sendResponse(false, 'Current password is incorrect');
            exit;
        }
        
        // Hash new password
        $hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);
        error_log('Manager API - New password hashed successfully');
        
        // Update password
        error_log('Manager API - Updating password for manager ID: ' . $manager_id);
        $stmt = $conn->prepare("UPDATE managers SET password = ?, updated_at = NOW() WHERE id = ?");
        if (!$stmt) {
            error_log('Manager API - Prepare failed for update: ' . $conn->error);
            sendResponse(false, 'Database error: ' . $conn->error);
            exit;
        }
        
        $stmt->bind_param("si", $hashedPassword, $manager_id);
        
        if ($stmt->execute()) {
            error_log('Manager API - Password updated successfully for ID: ' . $manager_id);
            sendResponse(true, 'Password changed successfully');
        } else {
            error_log('Manager API - Update failed: ' . $stmt->error);
            sendResponse(false, 'Failed to change password: ' . $stmt->error);
        }
    } catch (Exception $e) {
        error_log('Manager API - Exception: ' . $e->getMessage());
        sendResponse(false, 'Error: ' . $e->getMessage());
    }
}

// Get notification preferences
elseif ($action === 'getPreferences') {
    try {
        // For now, returning default preferences - in production, store these in database
        $preferences = [
            'emailNotifications' => true,
            'dailyReports' => true,
            'criticalAlerts' => true
        ];
        sendResponse(true, 'Preferences retrieved', $preferences);
    } catch (Exception $e) {
        sendResponse(false, 'Error: ' . $e->getMessage());
    }
}

// Save notification preferences
elseif ($action === 'savePreferences') {
    $data = json_decode(file_get_contents('php://input'), true);
    
    // In production, save these to database
    // For now, just confirm receipt
    sendResponse(true, 'Notification preferences saved successfully');
}

// Get profile information
elseif ($action === 'getProfile') {
    try {
        $manager = getManagerDetails($conn, $manager_id);
        if ($manager) {
            sendResponse(true, 'Profile retrieved', $manager);
        } else {
            sendResponse(false, 'Manager not found');
        }
    } catch (Exception $e) {
        sendResponse(false, 'Error: ' . $e->getMessage());
    }
}

// Get account status
elseif ($action === 'getStatus') {
    try {
        $stmt = $conn->prepare("SELECT id, name, email, status, last_login, created_at FROM managers WHERE id = ?");
        $stmt->bind_param("i", $manager_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $manager = $result->fetch_assoc();
            sendResponse(true, 'Status retrieved', $manager);
        } else {
            sendResponse(false, 'Manager not found');
        }
    } catch (Exception $e) {
        sendResponse(false, 'Error: ' . $e->getMessage());
    }
}

else {
    http_response_code(400);
    sendResponse(false, 'Invalid action');
}

$conn->close();
?>
