<?php
/**
 * Database Connection File
 * This file provides database connection configuration for the CRM system
 */

// Database credentials
define('DB_HOST', 'localhost');
define('DB_USER', 'u231988116_ominterior');
define('DB_PASS', 'P@55w0rd@m302303');
define('DB_NAME', 'u231988116_ominterior');

// Create mysqli connection to main CRM database
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// Check connection
if (!$conn) {
    die("Database connection failed: " . mysqli_connect_error());
}

// Set charset to utf8mb4
mysqli_set_charset($conn, "utf8mb4");
define('BASE_URL', 'https://ominteriorstudio.in/crm/');
/**
 * Helper function to get client-specific database connection
 * @param string $client_db_name Name of the client database
 * @return mysqli|null mysqli connection or null on failure
 */
function getClientConnection($client_db_name) {
    $client_conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, $client_db_name);
    if ($client_conn) {
        mysqli_set_charset($client_conn, "utf8mb4");
        return $client_conn;
    }
    return null;
}

/**
 * Helper function to escape strings for mysqli
 * @param string $string String to escape
 * @return string Escaped string
 */
function escapeString($string) {
    global $conn;
    return mysqli_real_escape_string($conn, $string);
}

/**
 * Verify that a project belongs to the logged-in user
 * This function ensures multi-user security by checking project ownership
 * 
 * @param int $project_id The project ID to verify
 * @param mysqli $conn Database connection
 * @return void - Dies with "Unauthorized Access" if verification fails
 */
function verifyProjectAccess($project_id, $conn) {
    // Start session if not already started
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    // Check if user is logged in
    if (!isset($_SESSION['user_id'])) {
        die("Unauthorized Access");
    }
    
    $user_id = $_SESSION['user_id'];
    $role = $_SESSION['user_role'] ?? 'Designer';

    // Admins have access to all projects
    if ($role === 'Admin') {
        return;
    }
    
    // Verify that the user is the creator or the assigned Master Designer
    $sql = "SELECT id FROM projects WHERE id = ? AND (created_by_user_id = ? OR master_designer_id = ?)";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('iii', $project_id, $user_id, $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        $stmt->close();
        die("Unauthorized Access");
    }
    
    $stmt->close();
}

/**
 * Verify that a design image belongs to the logged-in user
 * This function ensures multi-user security by checking project ownership of the image
 * 
 * @param int $design_image_id The design image ID to verify
 * @param mysqli $conn Database connection
 * @return void - Dies with "Unauthorized Access" if verification fails
 */
function verifyImageAccess($design_image_id, $conn) {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    if (!isset($_SESSION['user_id'])) {
        die("Unauthorized Access");
    }
    
    $user_id = $_SESSION['user_id'];
    $role = $_SESSION['user_role'] ?? 'Designer';

    // Admins have access to all images
    if ($role === 'Admin') {
        return;
    }
    
    $sql = "SELECT di.id 
            FROM design_images di
            JOIN projects p ON di.project_id = p.id
            WHERE di.id = ? AND (p.created_by_user_id = ? OR p.master_designer_id = ?)";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('iii', $design_image_id, $user_id, $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        $stmt->close();
        die("Unauthorized Access");
    }
    
    $stmt->close();
}

/**
 * Get projects that belong to the logged-in user
 * 
 * @param mysqli $conn Database connection
 * @return array Array of project records
 */
function getUserProjects($conn) {
    // Start session if not already started
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    // Check if user is logged in
    if (!isset($_SESSION['user_id'])) {
        return [];
    }
    
    $user_id = $_SESSION['user_id'];
    $role = $_SESSION['user_role'] ?? 'Designer';
    
    if ($role === 'Admin') {
        $sql = "SELECT p.id, p.project_name, c.client_name 
                FROM projects p 
                JOIN clients c ON p.client_id = c.id
                ORDER BY p.created_at DESC";
        $stmt = $conn->prepare($sql);
    } else {
        $sql = "SELECT p.id, p.project_name, c.client_name 
                FROM projects p 
                JOIN clients c ON p.client_id = c.id
                WHERE p.created_by_user_id = ? OR p.master_designer_id = ?
                ORDER BY p.created_at DESC";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('ii', $user_id, $user_id);
    }

    $stmt->execute();
    $result = $stmt->get_result();
    
    $projects = [];
    while ($row = $result->fetch_assoc()) {
        $projects[] = $row;
    }
    
    $stmt->close();
    return $projects;
}

/**
 * Check if the logged-in user has the required role to access a page
 */
function checkAccess() {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    if (!isset($_SESSION['user_id'])) {
        header("Location: index");
        exit;
    }

    $role = $_SESSION['user_role'] ?? null;

    // If role is empty or NULL
    if (empty($role)) {
        ?>
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
            <style>
                body { background-color: #f5f7fa; font-family: 'Inter', sans-serif; }
                .modal-content { border-radius: 16px; border: none; box-shadow: 0 15px 50px rgba(0,0,0,0.15); }
                .btn-primary { 
                    background: linear-gradient(135deg, #977C49, #7a633a); 
                    border: none; padding: 12px 40px; border-radius: 10px; font-weight: 600; 
                    box-shadow: 0 4px 12px rgba(151, 124, 73, 0.3);
                }
                .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 6px 15px rgba(151, 124, 73, 0.4); }
                .icon-box { width: 80px; height: 80px; background: rgba(151, 124, 73, 0.1); color: #977C49; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; font-size: 40px; }
            </style>
        </head>
        <body>
            <div class="modal fade" id="pendingModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-body text-center p-5">
                            <div class="icon-box"><i class="bi bi-shield-lock-fill"></i></div>
                            <h4 class="fw-bold text-dark mb-2">Access Pending</h4>
                            <p class="text-muted mb-4">Admin will assign role soon. please signin later.</p>
                            <button type="button" class="btn btn-primary" onclick="window.location.href='signin?logout=true'">OK</button>
                        </div>
                    </div>
                </div>
            </div>
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
            <script>
                window.onload = function() {
                    var myModal = new bootstrap.Modal(document.getElementById('pendingModal'));
                    myModal.show();
                };
            </script>
        </body>
        </html>
        <?php
        exit;
    }

    // Admin has full access
    if ($role === 'Admin') {
        return;
    }

    // Designer restrictions
    if ($role === 'Designer') {
        $allowed_pages = ['dashboard.php', 'projectlist.php', 'designimages.php', 'assignmentcalendar.php', 'taskmanager.php', 'imagepin.php'];
        $current_page = basename($_SERVER['PHP_SELF']);

        if (!in_array($current_page, $allowed_pages)) {
            header("Location: dashboard");
            exit;
        }
    }

    // Fail-safe for unrecognized roles
    if ($role !== 'Admin' && $role !== 'Designer') {
        die("Invalid role configuration. Please contact the administrator.");
    }
}
?>
