xNightR00T File Manager

Loading...
Current Directory:
Name Size Permission Modified Actions
Loading...
$ Waiting for command...
HEX
HEX
Server: LiteSpeed
System: Linux server701.web-hosting.com 4.18.0-553.45.1.lve.el8.x86_64 #1 SMP Wed Mar 26 12:08:09 UTC 2025 x86_64
User: artiksbn (3537)
PHP: 8.1.34
Disabled: NONE
Upload Files
File: //home/artiksbn/fidelity.artigianodellapizza.com/admin_functions.php
<?php
// admin_functions.php - Admin authentication and management
require_once 'config.php';
require_once 'customer_functions.php';

// Authenticate admin
function authenticateAdmin($username, $password) {
    $pdo = getDB();
    
    $stmt = $pdo->prepare("SELECT id, username, password FROM managers WHERE username = ?");
    $stmt->execute([$username]);
    $admin = $stmt->fetch();
    
    if ($admin && password_verify($password, $admin['password'])) {
        $_SESSION['admin_id'] = $admin['id'];
        $_SESSION['admin_username'] = $admin['username'];
        $_SESSION['admin_login_time'] = time();
        return true;
    }
    
    return false;
}

// Check if admin is logged in
function isAdminLoggedIn() {
    if (!isset($_SESSION['admin_id']) || !isset($_SESSION['admin_login_time'])) {
        return false;
    }
    
    // Check session timeout
    if (time() - $_SESSION['admin_login_time'] > ADMIN_SESSION_TIMEOUT) {
        adminLogout();
        return false;
    }
    
    // Update last activity time
    $_SESSION['admin_login_time'] = time();
    return true;
}

// Admin logout
function adminLogout() {
    unset($_SESSION['admin_id']);
    unset($_SESSION['admin_username']);
    unset($_SESSION['admin_login_time']);
}

// Get admin info
function getAdminInfo() {
    if (!isAdminLoggedIn()) {
        return null;
    }
    
    return [
        'id' => $_SESSION['admin_id'],
        'username' => $_SESSION['admin_username']
    ];
}

// Require admin login (redirect if not logged in)
function requireAdminLogin() {
    if (!isAdminLoggedIn()) {
        header('Location: admin.php?action=login');
        exit();
    }
}

// Get all customers with pagination and filtering
function getAllCustomers($page = 1, $limit = 20, $search = '', $status = 'active') {
    $pdo = getDB();
    $offset = ($page - 1) * $limit;
    
    // Initialize parameters array with status
    $params = [];
    $whereClause = "WHERE status = ?";
    $params[] = $status;
    
    // Add search conditions if search term is provided
    if (!empty($search)) {
        $whereClause .= " AND (first_name LIKE ? OR last_name LIKE ? OR phone_number LIKE ? OR customer_code LIKE ?)";
        $searchTerm = "%{$search}%";
        // Add search parameter 4 times for each OR condition
        $params[] = $searchTerm;
        $params[] = $searchTerm;
        $params[] = $searchTerm;
        $params[] = $searchTerm;
    }
    
    // Get total count
    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM customers {$whereClause}");
    $countStmt->execute($params);
    $total = $countStmt->fetchColumn();
    
    // Get customers
    $query = "
        SELECT *, 
               (SELECT COUNT(*) FROM transactions WHERE customer_id = customers.id) as total_transactions,
               (SELECT MAX(created_at) FROM transactions WHERE customer_id = customers.id) as last_transaction
        FROM customers 
        {$whereClause}
        ORDER BY created_at DESC 
        LIMIT ? OFFSET ?
    ";
    
    $stmt = $pdo->prepare($query);
    
    // Add limit and offset to params array
    $params[] = $limit;
    $params[] = $offset;
    
    // Execute with all parameters
    $stmt->execute($params);
    
    return [
        'customers' => $stmt->fetchAll(),
        'total' => $total,
        'pages' => ceil($total / $limit),
        'current_page' => $page
    ];
}

// Create new customer (admin)
function createCustomer($phone, $firstName = null, $lastName = null, $currentPoints = 0, $availablePizzas = 0) {
    $pdo = getDB();
    
    // Validate phone number
    $phone = validatePhoneNumber($phone);
    if (!$phone) {
        return ['success' => false, 'message' => 'Format de numéro de téléphone invalide'];
    }
    
    // Check if customer already exists
    $stmt = $pdo->prepare("SELECT id FROM customers WHERE phone_number = ?");
    $stmt->execute([$phone]);
    if ($stmt->fetch()) {
        return ['success' => false, 'message' => 'Numéro de téléphone déjà enregistré'];
    }
    
    // Generate customer code
    $customerCode = getNextCustomerCode();

    // Calculate points and pizzas
    $totalPoints = $currentPoints;
    $pizzasFromPoints = floor($totalPoints / POINTS_FOR_FREE_PIZZA);
    $remainingPoints = $totalPoints % POINTS_FOR_FREE_PIZZA;
    $totalPizzas = $availablePizzas + $pizzasFromPoints;
    
    $currentDateTime = getCurrentParisDateTimeString();
    
    try {
        $pdo->beginTransaction();

        $stmt = $pdo->prepare("
            INSERT INTO customers (phone_number, customer_code, first_name, last_name, current_points, available_free_pizzas, created_at, updated_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$phone, $customerCode, $firstName, $lastName, $remainingPoints, $totalPizzas, $currentDateTime, $currentDateTime]);
        
        $customerId = $pdo->lastInsertId();
        $adminInfo = getAdminInfo();

        if ($currentPoints > 0) {
            $details = "+{$currentPoints} point" . ($currentPoints > 1 ? 's' : '') . " (création client)";
            $stmt = $pdo->prepare("
                INSERT INTO transactions (customer_id, manager_id, type, details, created_at) 
                VALUES (?, ?, 'POINT_ADDITION', ?, ?)
            ");
            $stmt->execute([$customerId, $adminInfo['id'], $details, $currentDateTime]);
        }

        $pdo->commit();

        return [
            'success' => true, 
            'message' => 'Client créé avec succès',
            'customer_code' => $customerCode,
            'customer_id' => $customerId
        ];
    } catch (PDOException $e) {
        $pdo->rollBack();
        return ['success' => false, 'message' => 'Échec de la création du client'];
    }
}

// Update customer
function updateCustomer($customerId, $phone, $firstName = null, $lastName = null, $currentPoints = 0, $availablePizzas = 0) {
    $pdo = getDB();
    
    // Validate phone number
    $phone = validatePhoneNumber($phone);
    if (!$phone) {
        return ['success' => false, 'message' => 'Format de numéro de téléphone invalide'];
    }
    
    // Check if phone number exists for other customers
    $stmt = $pdo->prepare("SELECT id FROM customers WHERE phone_number = ? AND id != ?");
    $stmt->execute([$phone, $customerId]);
    if ($stmt->fetch()) {
        return ['success' => false, 'message' => 'Numéro de téléphone déjà utilisé par un autre client'];
    }

    $currentDateTime = getCurrentParisDateTimeString();

    try {
        $pdo->beginTransaction();

        $stmt = $pdo->prepare("SELECT current_points, available_free_pizzas FROM customers WHERE id = ?");
        $stmt->execute([$customerId]);
        $customer = $stmt->fetch();

        if (!$customer) {
            throw new Exception("Client non trouvé");
        }

        $pointsToAdd = $currentPoints - $customer['current_points'];

        // Calculate points and pizzas
        $totalPoints = $currentPoints;
        $pizzasFromPoints = floor($totalPoints / POINTS_FOR_FREE_PIZZA);
        $remainingPoints = $totalPoints % POINTS_FOR_FREE_PIZZA;
        $totalPizzas = $availablePizzas + $pizzasFromPoints;

        $stmt = $pdo->prepare("
            UPDATE customers 
            SET phone_number = ?, first_name = ?, last_name = ?, current_points = ?, available_free_pizzas = ?, updated_at = ?
            WHERE id = ?
        ");
        $stmt->execute([$phone, $firstName, $lastName, $remainingPoints, $totalPizzas, $currentDateTime, $customerId]);

        if ($pointsToAdd != 0) {
            $adminInfo = getAdminInfo();
            $details = ($pointsToAdd > 0 ? '+' : '') . "{$pointsToAdd} point" . (abs($pointsToAdd) > 1 ? 's' : '') . " (mise à jour admin)";
            $stmt = $pdo->prepare("
                INSERT INTO transactions (customer_id, manager_id, type, details, created_at) 
                VALUES (?, ?, 'POINT_ADDITION', ?, ?)
            ");
            $stmt->execute([$customerId, $adminInfo['id'], $details, $currentDateTime]);
        }

        $pdo->commit();
        
        return ['success' => true, 'message' => 'Client mis à jour avec succès'];
    } catch (Exception $e) {
        $pdo->rollBack();
        return ['success' => false, 'message' => 'Échec de la mise à jour du client: ' . $e->getMessage()];
    }
}

// Soft delete customer
function deactivateCustomer($customerId) {
    $pdo = getDB();
    
    try {
        $currentDateTime = getCurrentParisDateTimeString();
        $stmt = $pdo->prepare("UPDATE customers SET status = 'inactive', updated_at = ? WHERE id = ?");
        $stmt->execute([$currentDateTime, $customerId]);
        
        return ['success' => true, 'message' => 'Client désactivé avec succès'];
    } catch (PDOException $e) {
        return ['success' => false, 'message' => 'Échec de la désactivation du client'];
    }
}

// Reactivate customer
function reactivateCustomer($customerId) {
    $pdo = getDB();
    
    try {
        $currentDateTime = getCurrentParisDateTimeString();
        $stmt = $pdo->prepare("UPDATE customers SET status = 'active', updated_at = ? WHERE id = ?");
        $stmt->execute([$currentDateTime, $customerId]);
        
        return ['success' => true, 'message' => 'Client réactivé avec succès'];
    } catch (PDOException $e) {
        return ['success' => false, 'message' => 'Échec de la réactivation du client'];
    }
}

// Get customer details by ID
function getCustomerById($customerId) {
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT * FROM customers WHERE id = ?");
    $stmt->execute([$customerId]);
    return $stmt->fetch();
}

// Export transactions to CSV
function exportTransactionsCSV($startDate = null, $endDate = null, $transactionType = null) {
    $pdo = getDB();
    
    $whereClause = "WHERE 1=1";
    $params = [];
    
    if ($startDate) {
        $whereClause .= " AND DATE(t.created_at) >= :start_date";
        $params[':start_date'] = $startDate;
    }
    
    if ($endDate) {
        $whereClause .= " AND DATE(t.created_at) <= :end_date";
        $params[':end_date'] = $endDate;
    }
    
    if ($transactionType && $transactionType !== 'all') {
        $whereClause .= " AND t.type = :transaction_type";
        $params[':transaction_type'] = $transactionType;
    }
    
    $stmt = $pdo->prepare("
        SELECT 
            t.id,
            t.created_at as transaction_date,
            c.customer_code,
            c.phone_number,
            CONCAT(COALESCE(c.first_name, ''), ' ', COALESCE(c.last_name, '')) as customer_name,
            t.type as transaction_type,
            t.details,
            m.username as manager_username
        FROM transactions t
        JOIN customers c ON t.customer_id = c.id
        LEFT JOIN managers m ON t.manager_id = m.id
        {$whereClause}
        ORDER BY t.created_at DESC
    ");
    
    $stmt->execute($params);
    $transactions = $stmt->fetchAll();
    
    // Generate CSV content
    $csvContent = "ID,Date,Heure,Code Client,Téléphone,Nom Client,Type Transaction,Détails,Manager\n";
    
    foreach ($transactions as $transaction) {
        // DateTime is already in Paris timezone from database
        $transactionDate = formatDisplayDateTime($transaction['transaction_date'], 'Y-m-d');
        $transactionTime = formatDisplayDateTime($transaction['transaction_date'], 'H:i:s');
        
        $csvContent .= sprintf(
            "%d,%s,%s,%s,%s,%s,%s,%s,%s\n",
            $transaction['id'],
            $transactionDate,
            $transactionTime,
            $transaction['customer_code'],
            $transaction['phone_number'],
            '"' . trim($transaction['customer_name']) . '"',
            $transaction['transaction_type'],
            '"' . $transaction['details'] . '"',
            $transaction['manager_username']
        );
    }
    
    return $csvContent;
}

// Get transaction statistics
function getTransactionStats($startDate = null, $endDate = null) {
    $pdo = getDB();
    
    $whereClause = "WHERE 1=1";
    $params = [];
    
    if ($startDate) {
        $whereClause .= " AND DATE(created_at) >= :start_date";
        $params[':start_date'] = $startDate;
    }
    
    if ($endDate) {
        $whereClause .= " AND DATE(created_at) <= :end_date";
        $params[':end_date'] = $endDate;
    }
    
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as total_transactions,
            SUM(CASE WHEN type = 'POINT_ADDITION' THEN 1 ELSE 0 END) as point_additions,
            SUM(CASE WHEN type = 'PIZZA_REDEMPTION' THEN 1 ELSE 0 END) as pizza_redemptions,
            COUNT(DISTINCT customer_id) as unique_customers,
            DATE(MIN(created_at)) as first_transaction_date,
            DATE(MAX(created_at)) as last_transaction_date
        FROM transactions 
        {$whereClause}
    ");
    
    $stmt->execute($params);
    return $stmt->fetch();
}

// Get daily transaction summary
function getDailyTransactionSummary($startDate = null, $endDate = null) {
    $pdo = getDB();
    
    $whereClause = "WHERE 1=1";
    $params = [];
    
    if ($startDate) {
        $whereClause .= " AND DATE(created_at) >= :start_date";
        $params[':start_date'] = $startDate;
    }
    
    if ($endDate) {
        $whereClause .= " AND DATE(created_at) <= :end_date";
        $params[':end_date'] = $endDate;
    }
    
    $stmt = $pdo->prepare("
        SELECT 
            DATE(created_at) as transaction_date,
            COUNT(*) as total_transactions,
            SUM(CASE WHEN type = 'POINT_ADDITION' THEN 1 ELSE 0 END) as point_additions,
            SUM(CASE WHEN type = 'PIZZA_REDEMPTION' THEN 1 ELSE 0 END) as pizza_redemptions,
            COUNT(DISTINCT customer_id) as unique_customers
        FROM transactions 
        {$whereClause}
        GROUP BY DATE(created_at)
        ORDER BY transaction_date DESC
    ");
    
    $stmt->execute($params);
    return $stmt->fetchAll();
}

// Update admin password
function updateAdminPassword($adminId, $oldPassword, $newPassword) {
    $pdo = getDB();

    // Get current password hash
    $stmt = $pdo->prepare("SELECT password FROM managers WHERE id = ?");
    $stmt->execute([$adminId]);
    $admin = $stmt->fetch();

    if (!$admin) {
        return ['success' => false, 'message' => 'Admin non trouvé.'];
    }

    // Verify old password
    if (!password_verify($oldPassword, $admin['password'])) {
        return ['success' => false, 'message' => 'Ancien mot de passe incorrect.'];
    }

    $newPassword = password_hash($newPassword, PASSWORD_DEFAULT);

    // Update password
    try {
        $stmt = $pdo->prepare("UPDATE managers SET password = ? WHERE id = ?");
        $stmt->execute([$newPassword, $adminId]);

        return ['success' => true, 'message' => 'Mot de passe mis à jour avec succès.'];
    } catch (PDOException $e) {
        return ['success' => false, 'message' => 'Échec de la mise à jour du mot de passe.'];
    }
}

// Get recent transactions for dashboard
function getRecentTransactions($limit = 10) {
    $pdo = getDB();
    
    $stmt = $pdo->prepare("
        SELECT 
            t.id,
            t.created_at,
            t.type,
            t.details,
            c.customer_code,
            c.phone_number,
            CONCAT(COALESCE(c.first_name, ''), ' ', COALESCE(c.last_name, '')) as customer_name,
            m.username as manager_username
        FROM transactions t
        JOIN customers c ON t.customer_id = c.id
        LEFT JOIN managers m ON t.manager_id = m.id
        ORDER BY t.created_at DESC
        LIMIT ?
    ");
    
    $stmt->execute([$limit]);
    return $stmt->fetchAll();
}
?>