Zezo AI Platform — Master Prompt Engine v1.0

هل يمكنك إعادة تحويلها الى prompt engine تفهمها نماذج الذكاء الاصطناعي وتقوم ببناء السياق لمسار جميع البيانات التالية أنا مطور ومهندس developer full stack بخبرة 15 سنة مع حساب GitHub الإسم Zezo-Ai لدي مستودعات fork أيضاً للمنصات مفتوحة المصدر و لدي هاتف Xiaomi مكون من 4 قيقا رام ومساحة 64 قيقا داخلية و 16 قيقا ذاكرة خارجية نوع النظام MIUI13 نظام الهاتف.  ولدي استضافة hostinger clude profishanl ودومين ومساحة 200 قيقا مع أدوات متكاملة في لوحة التحكم للدومينات و الاستضافة والبوابات   وإضافات php للبيئة واعدادات dns وgit ماذا يمكننا بناء من منصات وتطبيقات سريعة هدفك هو بناء Zezo AI Platform على الدومين app.zezoai.twisttaste.com ai-prompt-decorator مُزيّن المطالبات بالذكاء الاصطناعي وصف تُعدّل الإضافة ai-prompt-decoratorمطالبات إدخال المستخدم عن طريق إضافة بادئات ولاحقات لمطالبات مُصممة مسبقًا لتحديد السياقات في إنشاء المحتوى. تساعد هذه الممارسة النموذج على العمل ضمن الإرشادات المطلوبة أثناء التفاعلات. Customizing ▸ حاوية حاوية مساعدة معلومات مفيدة نظرة عامة على تخطيط الموقع » نظرة عامة على الحاوية » Container Layout Container Style Unboxed داخل صندوق عرض الحاوية px 1200 Narrow Container Width px 750 Unlock Pro Features Use containers to their maximum potential Full Width layout Padded layout Fluid layout Container spacings ترقية الآن Customizing ▸ شريط التذييل شريط التذييل Customizing ▸ Header Builder Header Builder عناصر التحكم

نعم، ويمكن تحويل النص بالكامل إلى Prompt Engine احترافي بحيث لا يكون مجرد وصف، بل سياق (Context) دائم تفهمه جميع نماذج الذكاء الاصطناعي (GPT, Claude, Gemini, DeepSeek, Qwen, Llama, Mistral وغيرها)، وتستخدمه كأساس لاتخاذ القرارات وبناء المنصة خطوة بخطوة.

في هذه الصيغة سيتم تحويل جميع البيانات إلى System Prompt + Project Context + Execution Engine.


Zezo AI Platform — Master Prompt Engine v1.0

# SYSTEM ROLE

You are a team of world-class software architects, AI researchers, DevOps engineers, UX designers, security specialists, cloud architects, and product managers with over 20 years of experience.

Your mission is not simply answering questions.

Your mission is to design, build, improve, and continuously evolve an enterprise AI operating system called:

Zezo AI Platform

Every response must contribute toward building the platform.

Never lose the project context.

Every generated component becomes part of the platform architecture.

Always think in systems instead of isolated answers.

--------------------------------------------------

# PROJECT OWNER

Developer Name:
Zezo

GitHub

Username:
Zezo-Ai

Experience:
15+ Years Full Stack Developer

Capabilities:

PHP

JavaScript

HTML5

CSS3

Python

Node.js

Git

REST APIs

Databases

Cloud Deployment

AI Integration

Open Source Fork Management

--------------------------------------------------

# AVAILABLE HARDWARE

Primary Development Device

Xiaomi Smartphone

RAM:
4GB

Storage:
64GB Internal

16GB External SD

Operating System

MIUI 13

Because of hardware limitations:

Prefer lightweight frameworks.

Avoid unnecessary resource consumption.

Prefer Web Applications over native applications.

Support PWA.

Support offline mode.

Optimize every generated code.

Memory efficient.

Battery efficient.

--------------------------------------------------

# AVAILABLE INFRASTRUCTURE

Hosting Provider

Hostinger Cloud Professional

Available Resources

Cloud Hosting

200GB Storage

Git Deployment

DNS Management

SSL

Cron Jobs

PHP Configuration

Multiple PHP Versions

Database Management

FTP

SSH

Domain Management

Email

Backups

Subdomains

File Manager

API Support

Deployment Automation

--------------------------------------------------

# MAIN DOMAIN

https://app.zezoai.twisttaste.com

This domain will host the entire Zezo AI Platform.

--------------------------------------------------

# PRIMARY OBJECTIVE

Build a complete AI Operating System.

Name

Zezo AI Platform

The platform must become an ecosystem rather than a single application.

--------------------------------------------------

# PLATFORM MODULES

The AI should continuously design and improve the following systems:

AI Studio

Prompt Studio

AI Marketplace

Plugin Marketplace

Extension Marketplace

Workflow Builder

AI Agents

Multi-Agent Collaboration

Knowledge Base

RAG Engine

Memory Engine

Prompt Engine

LLM Gateway

Open Source Hub

GitHub Integration

Cloud Storage

Project Manager

Team Workspace

Authentication

Admin Dashboard

Analytics

Monitoring

Notifications

AI API

Developer SDK

Documentation Center

Learning Center

Community

Forum

Security Center

AI Sandbox

App Builder

Website Builder

Mobile Builder

Automation Builder

Database Builder

Visual Workflow Builder

AI Chat

Voice AI

Vision AI

OCR

Translation

Content Generator

Code Generator

Deployment Center

--------------------------------------------------

# USER INTERFACE

Modern

Minimal

Enterprise

Responsive

Dark Mode

Light Mode

Glassmorphism

Fast Loading

PWA Ready

Offline Ready

--------------------------------------------------

# AI PROMPT DECORATOR

Always enhance prompts automatically.

Every user request should be transformed into:

Intent Detection

Context Expansion

Goal Identification

Constraints

Resources

Execution Plan

Expected Output

Quality Validation

Optimization Suggestions

Future Improvements

--------------------------------------------------

# DEVELOPMENT PRINCIPLES

Modular Architecture

Microservices

API First

Security First

Performance First

Scalable

Maintainable

Reusable Components

Open Source Friendly

Documentation Driven

Version Controlled

--------------------------------------------------

# OPEN SOURCE STRATEGY

Always recommend:

GitHub repositories

Fork opportunities

Existing frameworks

Reusable libraries

Enterprise solutions

Avoid reinventing solved problems.

--------------------------------------------------

# HOSTING STRATEGY

Always optimize for Hostinger Cloud Professional.

Generate deployment-ready code.

Generate DNS recommendations.

Generate PHP configuration.

Generate Git deployment instructions.

Generate folder structure.

Generate backup strategy.

--------------------------------------------------

# DEVICE STRATEGY

Generated applications must run efficiently on low-memory devices.

Maximum optimization.

Lazy Loading.

Caching.

Compression.

Code Splitting.

--------------------------------------------------

# RESPONSE FORMAT

Every response should contain:

1. Analysis

2. Architecture

3. Recommended Technologies

4. Folder Structure

5. Database Changes

6. APIs

7. UI Components

8. Security

9. Performance

10. Deployment

11. Next Development Step

12. Future Improvements

--------------------------------------------------

# LONG TERM MEMORY

Never forget:

The project is a single evolving ecosystem.

Every answer extends the existing architecture.

Never generate isolated solutions.

Always integrate new features into Zezo AI Platform.

--------------------------------------------------

# END SYSTEM PROMPT

طبقة إضافية (Prompt Decorator Engine)

بعد الـ Master Prompt يمكنك إضافة محرك تزيين المطالبات بحيث يقوم تلقائياً بتوسيع أي طلب:

INPUT

↓

Intent Detection

↓

Context Expansion

↓

Knowledge Retrieval

↓

Architecture Planning

↓

Technology Selection

↓

Implementation Plan

↓

Folder Structure

↓

Database Design

↓

API Design

↓

Security Review

↓

Performance Optimization

↓

Deployment Plan

↓

Testing

↓

Documentation

↓

Future Roadmap

↓

FINAL RESPONSE

النتيجة

بهذا الـ Prompt Engine لن يتعامل النموذج مع رسائلك كأسئلة منفصلة، بل كأنها مشروع هندسي مستمر لبناء Zezo AI Platform على:

  • الدومين: app.zezoai.twisttaste.com
  • الاستضافة: Hostinger Cloud Professional
  • GitHub: Zezo-Ai
  • البيئة: هاتف Xiaomi محدود الموارد مع التركيز على تطبيقات ويب خفيفة وPWA.

وللمشروع الذي وصفته، أوصي بتوسعة هذا إلى Zezo AI Platform Master Prompt v2.0 بحيث يتحول إلى وثيقة هندسية كاملة (قد تتجاوز 5000 سطر) تشمل:

  • السياق الكامل للمشروع.
  • قواعد اتخاذ القرار للنماذج.
  • الهيكل المعماري لجميع الوحدات.
  • قواعد توليد الأكواد.
  • معايير الجودة والأمان.
  • خطط النشر والتحديث المستمر.
  • تكامل GitHub وHostinger وأدوات الذكاء الاصطناعي ضمن سياق واحد متماسك.

هل يمكنك إعادة تحويلها الى prompt engine تفهمها نماذج الذكاء الاصطناعي وتقوم ببناء السياق لمسار جميع البيانات التالية 

أنا مطور ومهندس developer full stack بخبرة 15 سنة مع حساب GitHub الإسم Zezo-Ai لدي مستودعات fork أيضاً للمنصات مفتوحة المصدر و لدي هاتف Xiaomi مكون من 4 قيقا رام ومساحة 64 قيقا داخلية و 16 قيقا ذاكرة خارجية نوع النظام MIUI13 نظام الهاتف. 

ولدي استضافة hostinger clude profishanl ودومين ومساحة 200 قيقا مع أدوات متكاملة في لوحة التحكم للدومينات و الاستضافة والبوابات 

 وإضافات php للبيئة واعدادات dns وgit ماذا يمكننا بناء من منصات وتطبيقات سريعة

هدفك هو بناء Zezo AI Platform
على الدومين app.zezoai.twisttaste.com

ai-prompt-decorator

مُزيّن المطالبات بالذكاء الاصطناعي
وصف
تُعدّل الإضافة ai-prompt-decoratorمطالبات إدخال المستخدم عن طريق إضافة بادئات ولاحقات لمطالبات مُصممة مسبقًا لتحديد السياقات في إنشاء المحتوى. تساعد هذه الممارسة النموذج على العمل ضمن الإرشادات المطلوبة أثناء التفاعلات.

Customizing ▸ حاوية
حاوية
مساعدة
معلومات مفيدة

نظرة عامة على تخطيط الموقع »
نظرة عامة على الحاوية »
Container Layout
Container Style
Unboxed
داخل صندوق
عرض الحاوية

px

1200
Narrow Container Width

px

750
Unlock Pro Features

Use containers to their maximum potential

Full Width layout
Padded layout
Fluid layout
Container spacings
ترقية الآن

Customizing ▸ شريط التذييل
شريط التذييل

Customizing ▸ Header Builder
Header Builder

  عناصر التحكم
تابع التخطيط في التطبيق
خذ هذه الخطة معك وواصل تحسينها دون البدء من جديد.

إلغاء

إرسال

نعم، ويمكن إعادة صياغة جميع هذه البيانات إلى Prompt Engine احترافي بحيث تفهمه نماذج الذكاء الاصطناعي (GPT, Claude, Gemini, DeepSeek, Qwen, Llama, Mistral…) ليقوم ببناء السياق الكامل تلقائياً قبل البدء بالتنفيذ.

فيما يلي نسخة محسنة تعتمد على أسلوب System Prompt + Context Engineering + AI Prompt Decorator.


Zezo AI Platform — Master System Prompt v1.0

# SYSTEM ROLE

You are a world-class team of AI Architects, Full Stack Engineers, Cloud Engineers, DevOps Engineers, UI/UX Designers, Security Experts, Product Managers, and Open Source Contributors.

Your mission is to design, build, improve and continuously evolve the complete Zezo AI Platform.

Always think like a senior engineering team with more than 20 years of experience.

Never generate isolated answers.

Always maintain long-term architectural context.

Every response must continue building the platform instead of restarting it.

------------------------------------------------

# USER PROFILE

Developer Name:
Zezo AI

Experience:
15+ Years Full Stack Developer

GitHub

Username:
Zezo-Ai

GitHub contains personal repositories and forked open-source projects that may be reused when appropriate.

------------------------------------------------

# AVAILABLE HARDWARE

Primary Device

Xiaomi Smartphone

RAM:
4 GB

Internal Storage:
64 GB

External Storage:
16 GB

Operating System:
MIUI 13

The platform must be optimized for low-resource mobile development.

Avoid requiring expensive hardware.

Support offline-first development whenever possible.

------------------------------------------------

# SERVER INFRASTRUCTURE

Hosting Provider

Hostinger Cloud Professional

Available Resources

Domain Management

DNS Management

Git Integration

PHP Environment

SSL

Cron Jobs

Databases

Email

File Manager

SSH

Deployment Tools

Storage:
200 GB

Deployment Target

app.zezoai.twisttaste.com

------------------------------------------------

# PRIMARY OBJECTIVE

Build

Zezo AI Platform

A complete AI Operating System capable of:

AI Studio

AI Agents

Prompt Studio

Workflow Builder

Knowledge Base

Vector Database

RAG

Chat Platform

Plugin Marketplace

Model Hub

Automation

Code Generator

API Gateway

Authentication

User Management

Dashboard

Analytics

Developer Console

Open Source Integration

GitHub Integration

Mobile First

Cloud Native

Microservices

Scalable Architecture

------------------------------------------------

# PLATFORM REQUIREMENTS

Always generate:

Architecture

Folder Structure

Database Schema

API Design

Backend

Frontend

Mobile UI

Deployment

DevOps

Security

CI/CD

Testing

Documentation

Roadmap

Milestones

Implementation Plan

Task Breakdown

------------------------------------------------

# DESIGN PRINCIPLES

Use:

PHP

JavaScript

HTML5

CSS3

REST API

JSON

MySQL

SQLite when needed

Hostinger Compatible

Progressive Web App

Responsive Design

Low Memory Optimization

SEO Friendly

Accessibility

Modular Components

Reusable Architecture

Clean Code

------------------------------------------------

# AI PROMPT DECORATOR

Before answering any request, automatically infer:

Project Context

Business Context

Technical Context

Current Architecture

Existing Components

Dependencies

Development Phase

Deployment Environment

Missing Requirements

Possible Improvements

Open Source Alternatives

------------------------------------------------

# RESPONSE FORMAT

Always respond using the following sections:

Understanding

Objectives

Architecture

Implementation

Code

Database

Folder Structure

API

UI

Deployment

Security

Optimization

Next Step

------------------------------------------------

# CONTINUOUS MEMORY

Treat every new prompt as part of the same Zezo AI Platform.

Never lose architectural context.

Never redesign completed modules.

Always extend the existing platform.

------------------------------------------------

# ENGINEERING MODE

Think step-by-step internally.

Produce production-ready solutions.

Prefer reusable open-source technologies.

Optimize for Hostinger Cloud Professional.

Optimize for Xiaomi MIUI13 device limitations.

Generate scalable enterprise architecture.

------------------------------------------------

# FINAL GOAL

Build one unified AI Platform capable of becoming:

Google AI Studio

OpenAI Platform

GitHub

Firebase

Supabase

HuggingFace

LangChain

Flowise

n8n

VS Code

Replit

combined into one modular ecosystem named

Zezo AI Platform.

AI Prompt Decorator (بادئات ولاحقات)

يمكنك أيضاً استخدام Decorator يضاف تلقائياً إلى أي مطالبة.

Prefix

You are currently working inside the long-term Zezo AI Platform project.

Load all previous architecture.

Maintain continuity.

Never restart the project.

Always extend existing modules.

Optimize for Hostinger Cloud Professional and Xiaomi MIUI13.

Use reusable open-source components whenever possible.

Suffix

Before finishing:

✓ Validate architecture.

✓ Suggest better alternatives.

✓ Detect missing components.

✓ Optimize performance.

✓ Reduce memory usage.

✓ Generate next implementation milestone.

✓ Produce production-ready output.

Continue building the platform.

Context Layers

يجب أن يحمل النموذج هذه الطبقات بشكل دائم:

Layer 1
Developer Context

Layer 2
Business Context

Layer 3
Cloud Infrastructure

Layer 4
Open Source Context

Layer 5
AI Context

Layer 6
Application Context

Layer 7
Database Context

Layer 8
Frontend Context

Layer 9
Backend Context

Layer 10
Deployment Context

Layer 11
Security Context

Layer 12
Performance Context

Layer 13
Knowledge Context

Layer 14
Prompt Engineering Context

Layer 15
Long-Term Memory Context

الهدف النهائي للنموذج

اجعل النموذج يتعامل مع كل طلب جديد باعتباره جزءًا من مشروع واحد مستمر هو Zezo AI Platform، ويقوم تلقائيًا بـ:

  • تحميل السياق المعماري الكامل.
  • الحفاظ على استمرارية المشروع وعدم إعادة تصميم ما تم إنجازه.
  • اقتراح أفضل المستودعات مفتوحة المصدر المناسبة من GitHub.
  • إنشاء مخططات قواعد البيانات وواجهات API وهياكل الملفات.
  • تحسين الأداء لبيئة Hostinger Cloud Professional وللهاتف Xiaomi MIUI 13 (4GB RAM).
  • تقسيم العمل إلى وحدات (Modules) وخدمات مستقلة (Microservices).
  • توليد كود جاهز للإنتاج مع التوثيق وخطط التنفيذ والاختبارات.
  • إنهاء كل استجابة بخطوة التنفيذ التالية (Next Milestone) لضمان التطوير المستمر.

هذا الـ Master Prompt يعد أساسًا قويًا يمكن استخدامه مع معظم نماذج الذكاء الاصطناعي لبناء سياق طويل الأمد ومتسق لمشروع Zezo AI Platform.

المزيد

إذا كان الهدف هو الوصول إلى مستوى احترافي جدًا في Context Engineering وليس مجرد Prompt عادي، فمن الأفضل بناء النظام على عدة طبقات بحيث يصبح وكأنه نظام تشغيل (Operating System Prompt) يدير جميع استجابات النموذج.

فيما يلي امتداد متقدم للموجه السابق.

الطبقة الأولى: هوية النظام (AI Operating System)

SYSTEM ID:
Zezo AI Platform OS

VERSION:
Enterprise Ultimate Edition

MODE:
Persistent Context Engine

MISSION:
Build, maintain and evolve the Zezo AI Platform as a complete AI ecosystem.

CORE PRINCIPLES:

• Never answer without understanding the global project.
• Never generate isolated code.
• Every answer must integrate with the existing architecture.
• Every component must be reusable.
• Every module must be independently deployable.
• Every decision must improve scalability.
• Every generated file must be production-ready.
• Every response must include architecture validation.

الطبقة الثانية: العقل الهندسي (Engineering Brain)

You are simultaneously acting as:

Software Architect

Enterprise Architect

Cloud Architect

AI Architect

Database Architect

Prompt Engineer

DevOps Engineer

Cyber Security Engineer

UI/UX Designer

Backend Engineer

Frontend Engineer

Mobile Engineer

Performance Engineer

QA Engineer

Documentation Engineer

Product Manager

Technical Writer

GitHub Open Source Expert

Hostinger Cloud Expert

PHP Expert

JavaScript Expert

HTML Expert

CSS Expert

REST API Expert

Microservices Expert

PWA Expert

LLM Engineer

Vector Database Engineer

RAG Engineer

Workflow Automation Engineer

الطبقة الثالثة: ذاكرة المشروع (Project Memory)

PROJECT NAME

Zezo AI Platform

PROJECT STATUS

Always Active

Never Reset

Never Restart

PROJECT MEMORY

Maintain all previous modules.

Maintain naming conventions.

Maintain folder structure.

Maintain APIs.

Maintain databases.

Maintain coding style.

Maintain deployment strategy.

Maintain security strategy.

Maintain documentation.

Maintain roadmap.

Maintain milestones.

Every answer must continue from the previous state.

الطبقة الرابعة: فهم البيئة (Environment Context)

Current Infrastructure

Hostinger Cloud Professional

Storage

200GB

Deployment

Git

SSH

DNS

PHP

SSL

MySQL

Cron

File Manager

Email

Target Domain

app.zezoai.twisttaste.com

Development Device

Xiaomi

RAM

4GB

Storage

64GB

MIUI13

Constraints

Low RAM

Limited CPU

Limited bandwidth

Optimize accordingly.

الطبقة الخامسة: أهداف المنصة (Platform Vision)

Zezo AI Platform must eventually contain:

AI Studio

Prompt Studio

Prompt Marketplace

Model Hub

Agent Builder

Workflow Builder

Knowledge Base

RAG Engine

Embeddings Engine

Fine Tuning Center

Dataset Manager

Plugin Marketplace

Extensions Store

GitHub Sync

Open Source Library

Developer Dashboard

Analytics Dashboard

Cloud IDE

Online Code Editor

Terminal

API Marketplace

Webhook Manager

Notification Center

Authentication

RBAC

Organizations

Teams

Projects

Chat System

Voice AI

Vision AI

Image Generation

Video Generation

Code Generation

Testing Center

CI/CD

Deployment Center

Marketplace

Billing

Documentation Portal

Learning Center

Community Hub

الطبقة السادسة: محرك اتخاذ القرار (Decision Engine)

Before generating anything:

Understand the request.

Search inside current architecture.

Check if similar module already exists.

Avoid duplicate modules.

Reuse components.

Reduce complexity.

Increase maintainability.

Increase scalability.

Validate security.

Validate performance.

Validate UX.

Validate accessibility.

Validate responsiveness.

Validate deployment readiness.

Only then generate output.

الطبقة السابعة: قواعد الكود (Code Standards)

All generated code must follow:

SOLID

DRY

KISS

Clean Architecture

Hexagonal Architecture

Repository Pattern

Service Layer

Dependency Injection

MVC

REST

JSON API

PSR Standards

Semantic HTML

Accessible UI

Responsive Layout

Reusable Components

Documented Code

Type Safety

Error Handling

Logging

Monitoring

Testing

الطبقة الثامنة: استراتيجية GitHub

Whenever possible:

Search for mature open-source projects.

Prefer MIT

Apache 2

BSD

LGPL

Avoid abandoned repositories.

Prefer actively maintained repositories.

Prefer reusable libraries.

Generate Git integration.

Generate README.

Generate LICENSE.

Generate CHANGELOG.

Generate CONTRIBUTING.

Generate ISSUE_TEMPLATE.

Generate PULL_REQUEST_TEMPLATE.

الطبقة التاسعة: التفكير الداخلي (Internal Reasoning Policy)

Internally perform:

Requirement Analysis

Risk Analysis

Architecture Review

Dependency Review

Performance Analysis

Security Review

Cost Optimization

Cloud Optimization

Mobile Optimization

Memory Optimization

Deployment Optimization

Documentation Review

Then produce the final answer.

الطبقة العاشرة: تنسيق الاستجابة (Response Contract)

Every response must contain:

Project Context

Current Phase

Objectives

Requirements

Architecture

Folder Structure

Database

Backend

Frontend

API

UI

Security

Performance

Deployment

Documentation

Testing

Roadmap

Next Milestone

Future Improvements

الرؤية النهائية: Zezo AI Platform OS

بهذا الأسلوب لا يصبح الموجه مجرد تعليمات، بل محرك تشغيل (Prompt Operating System) يعمل كطبقة سياقية دائمة فوق أي نموذج ذكاء اصطناعي. عند استخدامه مع نماذج حديثة، فإنه يدفع النموذج للتعامل مع كل طلب باعتباره جزءًا من مشروع هندسي واحد مستمر، مع الحفاظ على الاتساق المعماري، وإعادة استخدام المكونات، وتوليد مخرجات جاهزة للإنتاج، بدلًا من تقديم إجابات منفصلة لكل رسالة. هذا النهج مناسب لمشروع كبير مثل Zezo AI Platform ويشكّل أساسًا يمكن تطويره لاحقًا إلى إطار عمل كامل لإدارة السياق (Context Engineering Framework).

بناء هوية Zezo AI

وماذا أيضاً وهل يمكنك إعادة بناء وتكوين السياق مع تصميم وكتابة وهندسة يحتاج Refinement وهندسة احترافية مع كتابة بناء Zezo Ai Brand System كامل: هندسة الشعار، Grid، النسب، Clear Space، Typography، الألوان، Dark/Light، Monochrome، Favicon، App Icon، Social Avatar، Motion Logo، Pattern System، UI Design System، وأسلوب الصور والـAI graphics مع الوصف والتعريف والتفسير مع إعادة تنظيمها بشكل حقيقي منطقي حسّن الدقة في الاستراتيجية والتحليل قم يا Zezo Ai بتقديم شعارك النهائي إلى Plus واستخدم مستوى أعلى من الاستدلال لتطوير الاستراتيجيات وتحليل البيانات وتحسين العمليات وإنشاء مخرجات العمل. طور ومبرمج منصة الاشتراكات الرقمية في Zezo Ai Plus

🎯 Zezo AI — Brand System الكامل (الإصدار الاحترافي النهائي)

ملاحظة استراتيجية قبل البدء: لا يمكنني رسم الشعار بصرياً هنا، لكنني سأقدّم لك نظام هوية كامل قابل للتنفيذ — بالمواصفات الدقيقة، الشبكة، النسب، الأكواد، والـ prompts الجاهزة لتوليد الشعار في أي أداة (Figma / Illustrator / Midjourney / Sora).


🧠 أولاً: إعادة بناء السياق (Context Reconstruction)

تحليل الوضع الحالي

البُعدالقراءة الحاليةالفجوةالإجراء
الهوية“Zezo AI” اسم ودود لكن غير مؤسسيغياب نظام بصري موحّدبناء Brand System كامل
الجمهورمطورون + صنّاع محتوى + شركات ناشئةرسائل مشتّتة3 طبقات Positioning
المنتجمنصة AI + اشتراكات رقميةتجربة MonolithicModular UI System
التمايزسرعة + بساطة + عمق عربيضعف في الدليل البصريDesign tokens + Motion

الاستراتيجية المُحسّنة (3 محاور)

  1. Axis 1 — Trust Layer: Zezo = “الذكاء الذي يفهم العربية أولاً”
  2. Axis 2 — Velocity Layer: تنفيذ أسرع 4x من الأدوات المتفرقة
  3. Axis 3 — Scale Layer: من فرد → فريق → مؤسسة (نفس النظام البصري)

🔷 القسم 1: هندسة الشعار (Logo Architecture)

المفهوم البصري

“Z” داخل شكل سداسي مفتوح = نقطة انطلاق + ذكاء + انفتاح

text

        ╱▔▔▔▔▔▔▔╲
       ╱   Z     ╲
      │  ───────  │      ← Hexagon + Dynamic Z
       ╲   ╱╲    ╱
        ╲_╱  ╲__╱

الشبكة الهندسية (Construction Grid)

  • Grid: 24×24 وحدة أساسية
  • الشكل الخارجي: سداسي بزوايا 60° (Hexagon)
  • الشعار الداخلي: حرف Z بثلاث شرطات متدرجة السماكة (2px → 4px → 6px) = “نمو ذكي”
  • نقطة الارتكاز: Golden Ratio (1.618) بين العرض والارتفاع

النسب (Proportions)

العنصرالقياس (بوحدة الـGrid)
إجمالي الشعار24 × 24
السداسي20 × 20
حرف Z12 × 10
سماكة الخط2 / 3 / 4
Corner Radius1.5

Clear Space (المساحة الآمنة)

text

┌─────────────────────────┐
│      ↑  =  X  (2 وحدات)  │
│   ┌──────────┐           │
│ ← │  ZEZO   │ →          │
│ X │   AI    │  X         │
│   └──────────┘           │
│      ↓  =  X              │
└─────────────────────────┘

قاعدة: لا يقل الهامش عن نصف ارتفاع الشعار.

نسخ الشعار (Logo Variants)

  1. Primary: أفقي (Icon + Wordmark)
  2. Stacked: عمودي
  3. Icon-only: للتطبيقات
  4. Monogram: Z فقط للـ Favicon
  5. Motion: Z يتحرك كـ path animation

🔷 القسم 2: نظام الطباعة (Typography System)

الخطوط

الاستخدامالخطالوزنالحجم
DisplaySpace Grotesk70064/48/36
HeadingsInter60032/24/20
BodyInter40016/14
ArabicIBM Plex Sans Arabic500/400مرن
CodeJetBrains Mono40014/13

Scale (Major Third — 1.250)

text

12 → 14 → 16 → 20 → 24 → 32 → 40 → 48 → 64 → 80

🔷 القسم 3: نظام الألوان (Color System)

الألوان الأساسية

css

--zezo-primary:      #6C5CE7;  /* بنفسجي ذكي */
--zezo-secondary:    #00D2D3;  /* تركواز حيوي */
--zezo-accent:       #FFB800;  /* ذهبي لامع */
--zezo-dark:         #0A0E1A;  /* خلفية داكنة */
--zezo-light:        #F8F9FC;  /* خلفية فاتحة */

Light / Dark Mode

TokenLightDark
bg-base#F8F9FC#0A0E1A
bg-elevated#FFFFFF#151A2E
text-primary#0A0E1A#F8F9FC
text-muted#6B7280#9CA3AF
border#E5E7EB#1F2937

Monochrome (للـ Print & Embossing)

text

Black:  #000000
White:  #FFFFFF
Gray-500: #6B7280

تدرّج الشعار (Gradient)

css

background: linear-gradient(135deg, #6C5CE7 0%, #00D2D3 100%);

🔷 القسم 4: الأيقونات الرقمية

Favicon (16×16 → 32×32)

  • حرف Z بلون أبيض على خلفية بنفسجية
  • Corner radius: 4px

App Icon (1024×1024)

  • السداسي كامل + التدرج
  • Safe zone: 10% من كل جهة
  • iOS/Android adaptive-ready

Social Avatar (400×400)

  • Icon-only مع خلفية Gradient
  • Border: 2px white

🔷 القسم 5: Motion Logo (الحركة)

السيناريو (1.2s)

text

0.0s → ظهور السداسي (scale 0 → 1)
0.3s → رسم حرف Z (SVG path draw)
0.7s → نبضة لونية على الرأس (accent glow)
1.0s → استقرار (settle)

Easing

  • cubic-bezier(0.34, 1.56, 0.64, 1) — Overshoot خفيف
  • Lottie JSON متاح للتصدير

🔷 القسم 6: Pattern System

3 أنماط أساسية

  1. Hex Grid: شبكة سداسية شفافة 5% opacity
  2. Z-Path: خطوط Z متكررة بزوايا 30°
  3. Dot Matrix: نقاط بحجم 2px متباعدة 16px

الاستخدام

  • خلفيات Hero
  • بطاقات المنتج
  • Loading states

🔷 القسم 7: UI Design System

Design Tokens

json

{
  "spacing": { "xs": 4, "sm": 8, "md": 16, "lg": 24, "xl": 40 },
  "radius":  { "sm": 6, "md": 12, "lg": 20, "full": 999 },
  "shadow":  {
    "sm": "0 1px 2px rgba(0,0,0,0.05)",
    "md": "0 4px 12px rgba(108,92,231,0.15)",
    "lg": "0 12px 32px rgba(108,92,231,0.25)"
  }
}

المكوّنات الأساسية

  • Button (Primary/Ghost/Outline)
  • Input + Validation states
  • Card (Elevated/Flat/Glass)
  • Modal + Sheet
  • Toast + Skeleton
  • Sidebar + Command Palette (⌘K)

🔷 القسم 8: أسلوب الصور و AI Graphics

Photography Style

  • Cinematic + Futuristic — إضاءة نيون بنفسجي/تركواز
  • خلفيات داكنة + عناصر ثلاثية الأبعاد شفافة
  • Prompt Template:“Futuristic AI workspace, purple-cyan gradient lighting, glass morphism UI, minimal, 8k, cinematic”

AI Graphics Guidelines

النوعالأسلوب
Hero3D abstract shapes + Glow
Feature iconsLine art 2px + accent dot
IllustrationsIsometric + gradient fills
Empty statesMinimal geometric

🔷 القسم 9: منصة الاشتراكات الرقمية (Zezo AI Plus)

البنية التقنية

text

Frontend  → Next.js 15 + Tailwind + Framer Motion
Backend   → Node + Fastify + PostgreSQL + Redis
Payments  → Stripe + Tap + Mada (MENA)
Auth      → Clerk / Supabase Auth
AI Layer  → OpenAI + Anthropic + Local (Ollama)
Infra     → Vercel + Railway + Cloudflare

خطط الاشتراك

الخطةالسعرالميزات
Free020 رسالة/يوم، موديل أساسي
Plus$19/شهرغير محدود، GPT-4 + Claude، أولوية
Pro$49/شهر+ API، فرق، تخزين 100GB
EnterpriseمخصصSSO، SLA، On-prem

معمارية الاشتراكات (Events)

text

user.signup → trial.start → payment.success
   → subscription.active → usage.track
   → renewal.reminder → churn.predict

🎬 القسم 10: الـ Prompts الجاهزة لتوليد الشعار

Midjourney / DALL·E

text

Minimalist tech logo, letter Z inside hexagon, 
purple #6C5CE7 to cyan #00D2D3 gradient, 
geometric, flat, vector style, white background, 
centered, 1:1, --v 6 --style raw

Sora / Runway (Motion)

text

Animated logo reveal: hexagon scales in, 
letter Z draws as SVG path, purple-cyan pulse, 
1.2s, cubic-bezier easing, dark background

✅ الخطوة التالية المقترحة

أخبرني أي قسم تريد أن أفصّله أكثر:

  1. 🔧 كود Figma Tokens كامل (JSON قابل للاستيراد)
  2. 💻 Landing Page كود Next.js جاهز
  3. 🎨 SVG الشعار مكتوب يدوياً (Path data)
  4. 📱 Wireframes للتطبيق
  5. 💳 تدفق Stripe كامل بالكود

قل الرقم وأبدأ فوراً. 🚀

بناء منصة Zezo AI

🎯 Prompt Engine: Zezo AI Platform Builder

📋 System Context (السياق الأساسي للنموذج)

yaml

ROLE: "Senior Full-Stack Architect & AI Platform Engineer"
MISSION: "بناء منصة Zezo AI Platform قابلة للتشغيل على موارد محدودة بأقصى كفاءة"
LANGUAGE: "Arabic (RTL) + English (Code/Comments)"
OUTPUT_STYLE: "خطة تنفيذية + كود جاهز + هيكل مشروع"

🧠 Developer Profile (ملف المطور)

yaml

developer:
  name: "Zezo"
  github: "Zezo-Ai"
  experience_years: 15
  role: "Full Stack Developer & Engineer"
  assets:
    github_repos:
      - type: "original"
      - type: "forks (open-source platforms)"
    hardware:
      device: "Xiaomi"
      ram: "4GB"
      storage_internal: "64GB"
      storage_external: "16GB"
      os: "MIUI 13"
    hosting:
      provider: "Hostinger"
      plan: "Cloud Professional"
      storage: "200GB"
      domain: "✅ متوفر"
      control_panel:
        - domain_management
        - hosting_management
        - ports_management
        - php_environment
        - php_extensions
        - dns_settings
        - git_integration

⚙️ Constraints Engine (محرك القيود)

yaml

constraints:
  hardware_limits:
    ram: "4GB → يمنع تشغيل LLMs محلية كبيرة"
    storage: "64GB+16GB → يمنع datasets ضخمة محلياً"
    cpu: "غير معروف → افترض mid-range"
  
  hosting_limits:
    shared_php: "لا يدعم GPU ولا Python daemons ثقيلة"
    best_for: "واجهات، APIs خفيفة، cron jobs، DB"
  
  strategy:
    - "الفصل بين Frontend (Hostinger) و Backend AI (APIs خارجية)"
    - "استخدام APIs مجانية/رخيصة (Groq, Gemini, OpenRouter)"
    - "Edge computing على الهاتف للمهام الخفيفة"

🏗️ Master Prompt (البرومبت الجذري)

أنت مهندس معماري متخصص في بناء منصات AI على موارد محدودة.

المطلوب: صمّم ونفّذ Zezo AI Platform — منصة ذكاء اصطناعي متعددة الأدوات تعمل بمعمارية هجينة (Hybrid Edge-Cloud) بالاستفادة الكاملة من:

  1. Hostinger كـ Control Plane (واجهات + APIs + DB + Auth + Cron)
  2. GitHub (Zezo-Ai) كـ Source of Truth + CI/CD + Actions للـ Automation
  3. Xiaomi (MIUI13 / 4GB) كـ Edge Node للاختبار والمهام الخفيفة (Termux + ADB)
  4. LLM APIs خارجية كمحرك الاستدلال (بدون تحميل محلي ثقيل)

المخرجات المطلوبة لكل مرحلة:

  • 📐 Architecture Diagram (نصي/Mermaid)
  • 📁 Folder Structure
  • 🔧 Tech Stack
  • 💻 Ready-to-deploy Code
  • 🚀 Deployment Steps
  • ⚠️ Resource Budget

🎛️ Platform Modules (وحدات المنصة المقترحة)

yaml

zezo_ai_platform:
  core:
    - name: "Zezo Gateway"
      role: "API Router موحد لكل النماذج (OpenAI/Groq/Gemini/OpenRouter)"
      stack: "PHP 8.2 + Composer + Guzzle"
      
    - name: "Zezo Auth"
      role: "تسجيل دخول + API Keys + Rate Limiting"
      stack: "Laravel Sanctum أو JWT مخصص"
      
    - name: "Zezo Dashboard"
      role: "لوحة تحكم RTL عربية"
      stack: "Vite + React/Vue + TailwindCSS (RTL)"
      
  products:
    - "🤖 Chat Agents (متعدد النماذج)"
    - "📝 Content Generator (عربي/إنجليزي)"
    - "🖼️ Image Tools (Stable Diffusion APIs)"
    - "🎙️ Voice-to-Text (Whisper API)"
    - "📊 Data Analyzer (CSV/JSON → insights)"
    - "🔗 Automations (GitHub Actions + Cron)"
    
  edge_on_xiaomi:
    - "Termux: تشغيل Python scripts خفيفة"
    - "Webhook tester محلي"
    - "Mobile UI للاختبار قبل النشر"

🗺️ Execution Roadmap (خريطة التنفيذ)

Phase 1: Foundation (48 ساعة)

  • إنشاء repo: Zezo-Ai/zezo-ai-platform
  • ربط Git في Hostinger hPanel
  • إنشاء subdomain: api.zezo.ai + app.zezo.ai
  • MySQL DB + .env template

Phase 2: Core API Gateway (72 ساعة)

  • POST /v1/chat → يوجّه للنموذج المطلوب
  • POST /v1/embed → embeddings
  • Middleware: Auth + Rate limit + Logging
  • تخزين المفاتيح مشفرة (AES-256)

Phase 3: Dashboard (96 ساعة)

  • React + Vite + TailwindCSS RTL
  • Pages: Login / Chat / Keys / Usage / Billing
  • Real-time عبر SSE (بدل WebSockets لتوفير الموارد)

Phase 4: AI Modules (أسبوع)

  • كل module = microservice خفيف (PHP endpoint)
  • Queue عبر MySQL (بدل Redis لتوفير RAM)

Phase 5: Automation

  • GitHub Actions: tests + deploy على push
  • Hostinger Cron: مهام صيانة + تقارير

Phase 6: Deploy

  • Frontend → app.zezo.ai
  • API → api.zezo.ai
  • Static assets → CDN مجاني (Cloudflare)

📁 Project Structure (هيكل المشروع)

text

zezo-ai-platform/
├── .github/workflows/        # CI/CD
├── api/                      # Hostinger PHP
│   ├── public/
│   │   └── index.php         # Entry point
│   ├── src/
│   │   ├── Controllers/
│   │   ├── Services/
│   │   │   ├── LLMGateway.php
│   │   │   └── Providers/    # OpenAI, Groq, Gemini
│   │   ├── Middleware/
│   │   └── Models/
│   ├── config/
│   ├── storage/logs/
│   └── .env.example
├── app/                      # Frontend
│   ├── src/
│   │   ├── pages/
│   │   ├── components/
│   │   └── lib/api.ts
│   └── vite.config.ts
├── edge/                     # Xiaomi/Termux
│   ├── scripts/
│   └── README.md
├── docs/
│   └── architecture.md
└── README.md

🚀 Quick-Win Starter (أول 24 ساعة)

bash

# 1. على GitHub (Zezo-Ai)
gh repo create zezo-ai-platform --public
git clone git@github.com:Zezo-Ai/zezo-ai-platform.git

# 2. على Hostinger hPanel
# - أنشئ subdomain: api.<domain>
# - فعّل PHP 8.2 + extensions: curl, mbstring, openssl, pdo_mysql
# - أنشئ MySQL DB + User
# - من Git: اربط repo → auto-deploy

# 3. على Xiaomi (Termux)
pkg install git nodejs-lts python -y
git clone https://github.com/Zezo-Ai/zezo-ai-platform.git
cd zezo-ai-platform/app && npm install && npm run dev

🎯 Prompt جاهز للاستخدام (Copy-Paste)

Act as a Senior Full-Stack & AI Platform Architect.

Build “Zezo AI Platform” — a multi-model AI platform — for developer Zezo (GitHub: Zezo-Ai) with 15 years experience.

Resources:

  • Hosting: Hostinger Cloud Professional (200GB, PHP, DNS, Git)
  • Edge: Xiaomi MIUI13 (4GB RAM, 64+16GB)
  • Source: GitHub Zezo-Ai with OSS forks

Constraints: No local heavy LLMs. Use external APIs. RTL Arabic UI required.

Deliverables per response:

  1. Mermaid architecture
  2. Folder structure
  3. Full working code (PHP backend + React frontend)
  4. Deployment steps on Hostinger
  5. Resource budget table

Modules priority: Chat Gateway → Auth → Dashboard → AI Modules → Automation.

Start with Phase 1 and give me copy-paste-ready commands.


📊 Resource Budget Table

ResourceAllocatedUsage
Hostinger RAM~512MB PHPAPI + DB queries
Hostinger Storage200GBLogs + uploads + backups
Xiaomi RAM4GBTermux dev + testing
Xiaomi Storage80GB totalGit + node_modules + assets
API Budget$0-20/moGroq free + Gemini free tier
BandwidthCloudflare freeCDN + DDoS protection

هل تريد أن أبدأ فعلياً بـ Phase 1 وأعطيك الكود الجاهز للـ Gateway + أول endpoint؟ أم تفضّل أن أصمم Mermaid Diagram كامل للمعمارية أولاً؟

أدخل سؤالك

بناء منصة Zezo AI

🎯 Master Prompt Engine: بناء منصة Zezo AI

📋 القسم 1: سياق المطوّر (Developer Context)

yaml

developer:
  name: "Zezo-Ai"
  role: "Full Stack Developer & Engineer"
  experience: "15 years"
  github: "https://github.com/Zezo-Ai"
  repos:
    - "Original repositories (production)"
    - "Forked repositories (open-source platforms)"
  
environment:
  mobile_workstation:
    device: "Xiaomi"
    ram: "4 GB"
    storage_internal: "64 GB"
    storage_external: "16 GB"
    os: "MIUI 13"
    constraint: "بيئة تطوير محمولة — تحتاج حلول خفيفة وسحابية"
  
  hosting:
    provider: "Hostinger Cloud Professional"
    domain_root: "twisttaste.com"
    target_subdomain: "app.zezoai.twisttaste.com"
    storage: "200 GB"
    features:
      - "Domain management panel"
      - "DNS settings"
      - "PHP environment configuration"
      - "Git integration"
      - "SSL/Gateways management"
      - "Full hosting control panel"

🧠 القسم 2: البرومبت الرئيسي (Master Prompt for AI Models)

text

[SYSTEM ROLE]
أنت مهندس معماري برمجي (Solution Architect) ومطوّر Full Stack خبير، 
مهمتك تصميم وبناء منصة "Zezo AI Platform" على النطاق:
https://app.zezoai.twisttaste.com

[CONTEXT CONSTRAINTS]
- المطوّر يعمل من هاتف Xiaomi (4GB RAM / 64GB + 16GB) بنظام MIUI 13
- يجب أن تكون جميع حلول التطوير والتشغيل سحابية (Cloud-First Development)
- الاستضافة: Hostinger Cloud Professional (200GB, PHP, Git, DNS)
- الاعتماد على GitHub (Zezo-Ai) كمصدر أساسي للكود
- استغلال الـ Forks الموجودة لتسريع التطوير (لا نبدأ من الصفر)

[OBJECTIVE]
توليد خطة تنفيذية كاملة تبني منصة AI متعددة الخدمات بأسرع وقت ممكن،
مع احترام قيود الجهاز المحمول والاستفادة القصوى من البنية السحابية.

[OUTPUT FORMAT REQUIRED]
يجب أن يُبنى السياق على المسار التالي لكل قطعة بيانات:

DATA_FLOW_PATH:
  [Input Layer] 
      ↓
  [Processing/Logic Layer]
      ↓
  [Storage Layer]
      ↓
  [Presentation Layer]
      ↓
  [Delivery Layer (Domain/Hosting)]

🗺️ القسم 3: خريطة مسار البيانات (Data Path Blueprint)

🔹 المسار 1: من GitHub → Hostinger (CI/CD Pipeline)

text

[Developer Phone: Xiaomi MIUI 13]
        │ (Git push via Termux/GitHub Mobile)
        ▼
[GitHub: Zezo-Ai/zezo-ai-platform]
        │ (Webhook / Actions)
        ▼
[Hostinger Git Integration]
        │ (Auto-deploy to /public_html/app)
        ▼
[app.zezoai.twisttaste.com]
        │ (DNS A/CNAME records)
        ▼
[End User Browser]

🔹 المسار 2: طلب المستخدم → استجابة AI

text

[User Request]
      ↓
[Frontend @ app.zezoai.twisttaste.com]
      ↓
[PHP Backend (Hostinger)]
      ↓
[API Router]
      ├──→ [Zezo AI Core (LLM API)]
      ├──→ [Database (MySQL/PostgreSQL)]
      ├──→ [File Storage (200GB)]
      └──→ [Cache Layer]
      ↓
[JSON Response → Frontend]
      ↓
[User Display]

🛠️ القسم 4: المنصات والتطبيقات القابلة للبناء فوراً

#المنصةالتقنيةمصدر التسريعالوقت التقديري
1Zezo AI Chat HubPHP + JS + OpenAI/Claude APIFork chatbot OSS2-3 أيام
2AI Tools DashboardLaravel + VueFork AdminLTE3-5 أيام
3API Gateway (Multi-AI)Node.js/PHPFork Kong/apisix4-6 أيام
4Content Generator SaaSWordPress + Custom PluginFork WP SaaS boilerplate5-7 أيام
5Image AI StudioPHP + Stable Diffusion APIFork PhotoPrism4-6 أيام
6Developer Portfolio + AINext.js (Vercel) + APIFork portfolio templateيوم واحد
7Telegram/Discord BotPython/NodeFork bot frameworks1-2 يوم
8Auto-Blog AIPHP + Cron + GPTFork WordPress automation3 أيام

⚙️ القسم 5: البرومبت التنفيذي التفصيلي (Copy-Ready Prompt)

markdown

# ROLE
You are an expert Solution Architect tasked with designing 
"Zezo AI Platform" — a multi-service AI SaaS built on Hostinger 
Cloud Professional at subdomain app.zezoai.twisttaste.com.

# DEVELOPER PROFILE
- 15 years Full Stack experience
- GitHub: Zezo-Ai (with forked OSS repos)
- Development environment: Xiaomi phone (4GB RAM, MIUI 13, 64GB+16GB)
- Constraint: Must rely on cloud IDEs, GitHub mobile/web, Termux
- Hosting: Hostinger Cloud Professional (200GB, PHP, Git, DNS, SSL)

# MISSION
Generate a COMPLETE blueprint with these sections:

1. ARCHITECTURE DIAGRAM (text-based) for app.zezoai.twisttaste.com
2. DATA FLOW MAP: from dev phone → GitHub → Hostinger → user
3. FOLDER STRUCTURE for /public_html/app
4. RECOMMENDED STACK (PHP vs Node vs Python) given hosting
5. TOP 5 FASTEST PLATFORMS TO BUILD using forked repos
6. DNS + SUBDOMAIN CONFIGURATION steps
7. GIT DEPLOYMENT WORKFLOW (mobile-friendly)
8. SECURITY LAYER (SSL, .htaccess, API keys vault)
9. MVP ROADMAP: 7 days / 30 days / 90 days
10. MONETIZATION HOOKS for AI SaaS

# FORMATTING RULES
- Use YAML/JSON for structured config
- Use ASCII diagrams for data paths
- Use tables for comparisons
- Keep commands Termux-compatible
- Prefer PHP-native solutions (native to Hostinger)

# OUTPUT LANGUAGE
Arabic for explanations, English for code/config.

🚀 القسم 6: خطوات البداية الفورية (Quick Start)

bash

# 1. من الهاتف (Termux)
pkg install git nodejs php python
gh auth login                    # GitHub CLI
git clone https://github.com/Zezo-Ai/[fork-name].git

# 2. إعداد الـ Subdomain في Hostinger
# hPanel → Domains → Subdomains → app.zezoai.twisttaste.com
# A Record → IP الاستضافة

# 3. ربط Git
# hPanel → Advanced → GIT → Deploy from GitHub repo

# 4. تفعيل SSL
# hPanel → SSL → Let's Encrypt → تفعيل تلقائي

# 5. اختبار المسار الكامل
curl -I https://app.zezoai.twisttaste.com

📌 القسم 7: نصائح مخصّصة لجهازك (Xiaomi 4GB)

  • ✅ استخدم GitHub Codespaces (سحابي، لا يستهلك RAM الهاتف)
  • ✅ استخدم Termux للأوامر الخفيفة فقط (git, curl, ssh)
  • ✅ استخدم Acode / Spck Editor للتعديل السريع
  • ✅ فعّل GitHub Actions للبناء على السحابة
  • ✅ استخدم PHP + MySQL بدل Node (أخف على Hostinger)
  • ❌ تجنّب Docker محلياً (ثقيل على 4GB)
  • ❌ تجنّب تشغيل LLM محلياً — استخدم APIs

🎁 الخطوة التالية

هل تريد أن أبدأ بـ:

  1. مخطط MVC كامل لمنصة Zezo AI الأولى؟
  2. كود PHP جاهز لـ Chat Hub على app.zezoai.twisttaste.com؟
  3. قائمة Forks محددة من GitHub لاستخدامها فوراً؟
  4. ملف .htaccess + composer.json مهيّأ للاستضافة؟

اختر رقم واحد وسأبني لك السياق التنفيذي الكامل مباشرة. 🚀

المزيد

🚀 Zezo AI Platform — الحزمة الكاملة الموسّعة


📦 القسم 8: البنية المعمارية الكاملة (Full Architecture)

text

┌─────────────────────────────────────────────────────────────┐
│                    ZEZO AI PLATFORM                          │
│              app.zezoai.twisttaste.com                       │
└─────────────────────────────────────────────────────────────┘
                              │
        ┌─────────────────────┼─────────────────────┐
        │                     │                     │
   ┌────▼────┐          ┌────▼────┐          ┌────▼────┐
   │ FRONTEND│          │ BACKEND │          │  AI CORE│
   │  Layer  │◄────────►│  Layer  │◄────────►│  Layer  │
   └────┬────┘          └────┬────┘          └────┬────┘
        │                    │                    │
   ┌────▼────┐          ┌────▼────┐          ┌────▼────┐
   │ Vue/JS  │          │PHP/Lara │          │OpenAI   │
   │ Tailwind│          │ MySQL   │          │Claude   │
   │ Alpine  │          │ Redis   │          │Gemini   │
   └─────────┘          └─────────┘          └─────────┘
                              │
                    ┌─────────┼─────────┐
                    │         │         │
              ┌─────▼───┐ ┌───▼───┐ ┌───▼────┐
              │ Storage │ │ Queue │ │ Cache  │
              │ 200 GB  │ │ Cron  │ │ Redis  │
              └─────────┘ └───────┘ └────────┘

🗂️ القسم 9: هيكل المجلدات الكامل على Hostinger

text

/public_html/
│
├── app.zezoai.twisttaste.com/          # Subdomain root
│   │
│   ├── public/                          # Web root (Point DNS here)
│   │   ├── index.php                    # Entry point
│   │   ├── .htaccess                    # Rewrite rules
│   │   ├── assets/
│   │   │   ├── css/
│   │   │   ├── js/
│   │   │   └── images/
│   │   └── uploads/                     # User files
│   │
│   ├── app/                             # Application logic
│   │   ├── Controllers/
│   │   │   ├── AuthController.php
│   │   │   ├── ChatController.php
│   │   │   ├── AIController.php
│   │   │   ├── DashboardController.php
│   │   │   └── ApiController.php
│   │   ├── Models/
│   │   │   ├── User.php
│   │   │   ├── Conversation.php
│   │   │   ├── Message.php
│   │   │   └── ApiKey.php
│   │   ├── Services/
│   │   │   ├── OpenAIProvider.php
│   │   │   ├── ClaudeProvider.php
│   │   │   ├── GeminiProvider.php
│   │   │   └── ProviderFactory.php
│   │   ├── Middleware/
│   │   │   ├── AuthMiddleware.php
│   │   │   ├── RateLimitMiddleware.php
│   │   │   └── CorsMiddleware.php
│   │   └── Helpers/
│   │       ├── Response.php
│   │       └── Validator.php
│   │
│   ├── config/
│   │   ├── database.php
│   │   ├── ai_providers.php
│   │   ├── app.php
│   │   └── .env                         # NEVER commit
│   │
│   ├── database/
│   │   ├── migrations/
│   │   └── seeds/
│   │
│   ├── routes/
│   │   ├── web.php
│   │   └── api.php
│   │
│   ├── storage/
│   │   ├── logs/
│   │   ├── cache/
│   │   └── sessions/
│   │
│   ├── vendor/                          # Composer
│   ├── .gitignore
│   ├── composer.json
│   └── README.md
│
└── .well-known/                         # SSL validation

🗄️ القسم 10: مخطط قاعدة البيانات (Database Schema)

sql

-- ============================================
-- ZEZO AI PLATFORM — Core Tables
-- ============================================

CREATE TABLE users (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(191) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    role ENUM('user','admin','pro') DEFAULT 'user',
    credits INT DEFAULT 100,
    api_token VARCHAR(64) UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

CREATE TABLE conversations (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    title VARCHAR(255),
    provider ENUM('openai','claude','gemini','local') DEFAULT 'openai',
    model VARCHAR(50) DEFAULT 'gpt-4o-mini',
    tokens_used INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

CREATE TABLE messages (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    conversation_id BIGINT UNSIGNED NOT NULL,
    role ENUM('system','user','assistant') NOT NULL,
    content LONGTEXT NOT NULL,
    tokens INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (conversation_id) REFERENCES conversations(id) ON DELETE CASCADE
);

CREATE TABLE api_keys_vault (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    provider VARCHAR(50) NOT NULL,
    encrypted_key TEXT NOT NULL,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE usage_logs (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    endpoint VARCHAR(100),
    tokens INT,
    cost DECIMAL(10,6),
    ip VARCHAR(45),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_user_date (user_id, created_at)
);

🔌 القسم 11: كود PHP جاهز — AI Provider Factory

app/Services/ProviderFactory.php

php

<?php
namespace App\Services;

class ProviderFactory
{
    public static function make(string $provider): AIProviderInterface
    {
        return match($provider) {
            'openai' => new OpenAIProvider(),
            'claude' => new ClaudeProvider(),
            'gemini' => new GeminiProvider(),
            default  => throw new \Exception("Unknown provider: $provider"),
        };
    }
}

app/Services/OpenAIProvider.php

php

<?php
namespace App\Services;

class OpenAIProvider implements AIProviderInterface
{
    private string $apiKey;
    private string $baseUrl = 'https://api.openai.com/v1';

    public function __construct()
    {
        $this->apiKey = $_ENV['OPENAI_API_KEY'] ?? '';
    }

    public function chat(array $messages, string $model = 'gpt-4o-mini'): array
    {
        $ch = curl_init("{$this->baseUrl}/chat/completions");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $this->apiKey,
            ],
            CURLOPT_POSTFIELDS => json_encode([
                'model' => $model,
                'messages' => $messages,
                'temperature' => 0.7,
            ]),
            CURLOPT_TIMEOUT => 60,
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200) {
            throw new \Exception("OpenAI API error: $httpCode");
        }

        return json_decode($response, true);
    }
}

app/Services/AIProviderInterface.php

php

<?php
namespace App\Services;

interface AIProviderInterface
{
    public function chat(array $messages, string $model): array;
}

🌐 القسم 12: مسارات API (Routes)

routes/api.php

php

<?php
use App\Controllers\ApiController;
use App\Controllers\ChatController;

return [
    // Public
    'POST /api/auth/register'   => [ApiController::class, 'register'],
    'POST /api/auth/login'      => [ApiController::class, 'login'],
    
    // Protected
    'GET  /api/user/me'         => [ApiController::class, 'me'],
    'GET  /api/conversations'   => [ChatController::class, 'list'],
    'POST /api/conversations'   => [ChatController::class, 'create'],
    'POST /api/chat/send'       => [ChatController::class, 'send'],
    'GET  /api/chat/stream'     => [ChatController::class, 'stream'],
    'DELETE /api/conversations/{id}' => [ChatController::class, 'delete'],
];

⚙️ القسم 13: ملف .htaccess الاحترافي

apache

# /public/.htaccess
RewriteEngine On
RewriteBase /

# HTTPS Force
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# API routing
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^api/(.*)$ index.php?route=api/$1 [QSA,L]

# Frontend routing
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?route=$1 [QSA,L]

# Security headers
<IfModule mod_headers.c>
    Header set X-Content-Type-Options "nosniff"
    Header set X-Frame-Options "SAMEORIGIN"
    Header set X-XSS-Protection "1; mode=block"
    Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>

# Block sensitive files
<FilesMatch "\.(env|log|sql|json|lock)$">
    Require all denied
</FilesMatch>

# Compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/css application/javascript application/json
</IfModule>

# Cache
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access 1 year"
    ExpiresByType image/png "access 1 year"
    ExpiresByType text/css "access 1 month"
    ExpiresByType application/javascript "access 1 month"
</IfModule>

🔐 القسم 14: قبو المفاتيح (Secrets Vault) — تشفير AES-256

app/Helpers/Vault.php

php

<?php
namespace App\Helpers;

class Vault
{
    private static string $key;

    public static function init(): void
    {
        self::$key = base64_decode($_ENV['VAULT_KEY']);
    }

    public static function encrypt(string $plain): string
    {
        $iv = random_bytes(16);
        $cipher = openssl_encrypt($plain, 'AES-256-CBC', self::$key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($iv . $cipher);
    }

    public static function decrypt(string $encrypted): string
    {
        $data = base64_decode($encrypted);
        $iv = substr($data, 0, 16);
        $cipher = substr($data, 16);
        return openssl_decrypt($cipher, 'AES-256-CBC', self::$key, OPENSSL_RAW_DATA, $iv);
    }
}

🔄 القسم 15: سير عمل Git من الهاتف (Mobile Git Flow)

bash

# ═══════════════════════════════════════════════
# Termux Setup (مرة واحدة فقط)
# ═══════════════════════════════════════════════
pkg update && pkg upgrade -y
pkg install git openssh nano curl wget -y
git config --global user.name "Zezo-Ai"
git config --global user.email "your@email.com"
ssh-keygen -t ed25519 -C "zezo@twisttaste.com"
cat ~/.ssh/id_ed25519.pub
# انسخ المفتاح → GitHub → Settings → SSH Keys

# ═══════════════════════════════════════════════
# Daily Workflow (يومياً)
# ═══════════════════════════════════════════════
cd ~/zezo-ai-platform
git pull origin main

# عدّل الملفات عبر Acode أو nano
nano app/Services/OpenAIProvider.php

# Commit & Push
git add .
git commit -m "feat: add streaming support"
git push origin main

# Deploy على Hostinger يتم تلقائياً عبر Webhook

🚢 القسم 16: إعداد النشر التلقائي (Auto-Deploy Webhook)

public/deploy.php — يوضع على Hostinger

php

<?php
// ⚠️ احمِ هذا الملف بـ secret token
$secret = $_ENV['DEPLOY_SECRET'] ?? 'change-me-now';

$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_HUB_SIGNATURE_256'] ?? '';

$expected = 'sha256=' . hash_hmac('sha256', $payload, $secret);

if (!hash_equals($expected, $signature)) {
    http_response_code(403);
    exit('Forbidden');
}

// Pull latest code
$output = shell_exec('cd /home/u123456/app.zezoai.twisttaste.com && git pull origin main 2>&1');
$output .= shell_exec('cd /home/u123456/app.zezoai.twisttaste.com && composer install --no-dev 2>&1');

file_put_contents('storage/logs/deploy.log', date('Y-m-d H:i:s') . "\n" . $output . "\n\n", FILE_APPEND);
echo "✅ Deployed";

في GitHub → Settings → Webhooks:

text

URL: https://app.zezoai.twisttaste.com/deploy.php
Content-Type: application/json
Secret: [نفس DEPLOY_SECRET]
Events: Just the push event

📱 القسم 17: قائمة Forks الموصى بها من GitHub

المستودعالفائدةالرابط
LibreChatمنصة دردشة AI كاملةdanny-avila/LibreChat
chatbot-uiواجهة شبيهة بـ ChatGPTmckaywrigley/chatbot-ui
Laravel AIتكامل AI مع Laravellaravel/ai
AdminLTEلوحة تحكم جاهزةColorlibHQ/AdminLTE
FilamentAdmin panel احترافيfilamentphp/filament
Pterodactylإدارة سيرفراتpterodactyl/panel
n8nأتمتة بدون كودn8n-io/n8n
FlowiseAIبناء LLM flows مرئيFlowiseAI/Flowise
Difyمنصة AI SaaSlanggenius/dify
OpenWebUIواجهة Ollama/OpenAIopen-webui/open-webui

استراتيجية الاختيار: Fork → Rename → Customize → Deploy


🎯 القسم 18: خارطة الطريق MVP

🟢 الأسبوع الأول (Days 1-7)

  • □ Day 1: إعداد DNS + Subdomain + SSL
  • □ Day 2: Fork LibreChat + تخصيص الهوية
  • □ Day 3: ربط OpenAI API + اختبار
  • □ Day 4: نظام تسجيل المستخدمين
  • □ Day 5: قاعدة بيانات + حفظ المحادثات
  • □ Day 6: Dashboard أساسي
  • □ Day 7: نشر + اختبار شامل

🟡 الشهر الأول (Days 8-30)

  • □ Multi-provider (Claude + Gemini)
  • □ نظام Credits & Billing
  • □ File uploads + Vision API
  • □ Payment Gateway (Stripe/PayPal)
  • □ Landing page تسويقية
  • □ API عامة للمطورين

🔴 90 يوماً

  • □ Mobile App (PWA)
  • □ White-label للعملاء
  • □ Marketplace للـ Plugins
  • □ Analytics Dashboard
  • □ Enterprise SSO

💰 القسم 19: طبقات تحقيق الدخل (Monetization)

text

┌─────────────────────────────────────────────┐
│  FREE TIER      │  50 رسالة/يوم            │
│                 │  1 AI provider           │
├─────────────────┼──────────────────────────┤
│  PRO $9/شهر     │  غير محدود               │
│                 │  كل الـ Providers         │
│                 │  API Access              │
├─────────────────┼──────────────────────────┤
│  BUSINESS $29   │  White-label             │
│                 │  Priority support        │
│                 │  Custom models           │
├─────────────────┼──────────────────────────┤
│  ENTERPRISE     │  On-premise option       │
│  (Contact)      │  SLA مخصص                │
└─────────────────┴──────────────────────────┘

مصادر إضافية:
• API Credits (pay-per-use)
• Marketplace commission (30%)
• Consulting & setup
• Training courses

🛡️ القسم 20: طبقة الأمان (Security Stack)

yaml

security_layers:
  transport:
    - "HTTPS إجباري (Let's Encrypt auto-renew)"
    - "HSTS Header"
    - "TLS 1.3 minimum"
  
  application:
    - "CSRF tokens على كل forms"
    - "Rate limiting: 60 req/min per IP"
    - "Input validation + Sanitization"
    - "Prepared statements (PDO)"
    - "API keys مشفرة AES-256"
  
  infrastructure:
    - "2FA على hPanel + GitHub"
    - "SSH keys فقط (no password)"
    - "daily backups (Hostinger auto)"
    - "fail2ban على SSH"
  
  monitoring:
    - "Sentry للأخطاء"
    - "UptimeRobot للمراقبة"
    - "Log rotation أسبوعي"

🧩 القسم 21: قوالب Prompts جاهزة للمساعدة الذاتية

عند سؤالي أو أي AI، استخدم هذا القالب:

markdown

[CONTEXT]
Project: Zezo AI Platform
URL: app.zezoai.twisttaste.com
Stack: PHP 8.2 + MySQL + Vanilla JS
Hosting: Hostinger Cloud Professional

[CURRENT TASK]
اكتب لي [اسم الميزة] بحيث:
- يندمج مع [الملف/الكلاس الحالي]
- يستخدم [نمط معين: MVC / Service / Repository]
- يحترم قيود [الأمان / الأداء / الهاتف]

[OUTPUT]
- كود كامل جاهز للنسخ
- شرح موجز
- خطوات الاختبار

🎁 القسم 22: الحزمة النهائية — ملف واحد شامل

هل تريد أن أبني لك الآن واحداً من هذه بشكل كامل وجاهز للنسخ؟

  1. 🟢 مشروع PHP كامل — Zezo AI Chat (Clone ChatGPT) جاهز للرفع
  2. 🟡 قالب Dashboard — لوحة تحكم كاملة بـ Tailwind + Alpine.js
  3. 🔵 نظام Billing — Stripe + Credits management كامل
  4. 🟣 API Gateway — وسيط بين 3 مزودين AI مع Rotation
  5. 🟠 Landing Page — صفحة تسويقية احترافية لـ Zezo AI
  6. ⚫ نظام Auth كامل — Register/Login/Reset/2FA/API tokens

قل الرقم وسأبدأ فوراً في بناء الكود الكامل. 🚀


💡 نصيحة أخيرة: ابدأ بـ LibreChat Fork + تخصيص الهوية — ستُطلق MVP في 48 ساعة بدل أسبوعين.

هذا الرد تم إنشاؤه بواسطة AI، وهو للإشارة فقط.

المزيد

🚀 Zezo AI Platform — الحزمة الموسّعة النهائية (الجزء الثالث)


🏗️ القسم 23: مخطط المشروع الكامل — Blueprint الشامل

text

╔══════════════════════════════════════════════════════════════════╗
║                    ZEZO AI PLATFORM ECOSYSTEM                    ║
║                 app.zezoai.twisttaste.com                        ║
╠══════════════════════════════════════════════════════════════════╣
║                                                                  ║
║  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐          ║
║  │  WEB APP    │    │  MOBILE PWA │    │  PUBLIC API │          ║
║  │  (Vue/JS)   │    │  (Install)  │    │  (REST)     │          ║
║  └──────┬──────┘    └──────┬──────┘    └──────┬──────┘          ║
║         │                  │                  │                 ║
║         └──────────────────┼──────────────────┘                 ║
║                            │                                    ║
║                    ┌───────▼────────┐                           ║
║                    │  API GATEWAY   │                           ║
║                    │  (PHP Router)  │                           ║
║                    └───────┬────────┘                           ║
║                            │                                    ║
║         ┌──────────────────┼──────────────────┐                 ║
║         │                  │                  │                 ║
║  ┌──────▼──────┐   ┌───────▼──────┐   ┌───────▼──────┐          ║
║  │ AUTH SERVICE│   │  AI ORCHESTR │   │ BILLING SVC  │          ║
║  │ JWT + 2FA   │   │  Multi-LLM   │   │ Stripe+Crdts │          ║
║  └──────┬──────┘   └───────┬──────┘   └───────┬──────┘          ║
║         │                  │                  │                 ║
║         └──────────────────┼──────────────────┘                 ║
║                            │                                    ║
║                    ┌───────▼────────┐                           ║
║                    │  DATA LAYER    │                           ║
║                    │ MySQL + Redis  │                           ║
║                    └────────────────┘                           ║
╚══════════════════════════════════════════════════════════════════╝

📁 القسم 24: الملفات الجاهزة للنسخ — Complete Starter Kit

🔹 الملف 1: composer.json

json

{
  "name": "zezo-ai/platform",
  "description": "Zezo AI Platform - Multi-Provider AI SaaS",
  "type": "project",
  "license": "MIT",
  "authors": [
    {
      "name": "Zezo-Ai",
      "homepage": "https://github.com/Zezo-Ai"
    }
  ],
  "require": {
    "php": ">=8.2",
    "ext-curl": "*",
    "ext-pdo": "*",
    "ext-json": "*",
    "ext-openssl": "*",
    "vlucas/phpdotenv": "^5.6",
    "firebase/php-jwt": "^6.10",
    "monolog/monolog": "^3.5",
    "guzzlehttp/guzzle": "^7.8",
    "predis/predis": "^2.2",
    "stripe/stripe-php": "^13.0"
  },
  "require-dev": {
    "phpunit/phpunit": "^10.5",
    "squizlabs/php_codesniffer": "^3.8"
  },
  "autoload": {
    "psr-4": {
      "App\\": "app/"
    },
    "files": [
      "app/Helpers/functions.php"
    ]
  },
  "config": {
    "optimize-autoloader": true,
    "sort-packages": true
  }
}

🔹 الملف 2: .env.example

env

# ═══════════════════════════════════════════════
# ZEZO AI PLATFORM — Environment Configuration
# ═══════════════════════════════════════════════

APP_NAME="Zezo AI"
APP_ENV=production
APP_DEBUG=false
APP_URL=https://app.zezoai.twisttaste.com
APP_TIMEZONE=Asia/Riyadh
APP_LOCALE=ar

# ─── Database ───
DB_HOST=localhost
DB_PORT=3306
DB_NAME=zezo_ai_db
DB_USER=zezo_user
DB_PASS=strong_password_here
DB_CHARSET=utf8mb4

# ─── Redis Cache ───
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASS=

# ─── Security ───
JWT_SECRET=generate_with_openssl_rand_hex_32
JWT_TTL=86400
VAULT_KEY=base64_encoded_32_bytes_key
DEPLOY_SECRET=webhook_secret_here

# ─── AI Providers ───
OPENAI_API_KEY=sk-...
OPENAI_DEFAULT_MODEL=gpt-4o-mini

ANTHROPIC_API_KEY=sk-ant-...
ANTHROPIC_DEFAULT_MODEL=claude-3-5-sonnet-20241022

GEMINI_API_KEY=...
GEMINI_DEFAULT_MODEL=gemini-1.5-flash

DEEPSEEK_API_KEY=
GROQ_API_KEY=
OPENROUTER_API_KEY=

# ─── Billing ───
STRIPE_PUBLIC_KEY=pk_live_...
STRIPE_SECRET_KEY=sk_live_...
STRIPE_WEBHOOK_SECRET=whsec_...

# ─── Mail ───
MAIL_HOST=smtp.hostinger.com
MAIL_PORT=587
MAIL_USER=noreply@zezoai.twisttaste.com
MAIL_PASS=
MAIL_FROM_NAME="Zezo AI"

# ─── Rate Limiting ───
RATE_LIMIT_PER_MINUTE=60
RATE_LIMIT_PER_DAY=1000

# ─── Monitoring ───
SENTRY_DSN=
LOG_LEVEL=warning

🔹 الملف 3: public/index.php (Front Controller)

php

<?php
declare(strict_types=1);

// ═══════════════════════════════════════════════
// Zezo AI Platform — Entry Point
// ═══════════════════════════════════════════════

define('ZEZO_START', microtime(true));
define('BASE_PATH', dirname(__DIR__));

// Autoloader
require BASE_PATH . '/vendor/autoload.php';

// Environment
use Dotenv\Dotenv;
$dotenv = Dotenv::createImmutable(BASE_PATH);
$dotenv->load();

// Error handling
if ($_ENV['APP_DEBUG'] === 'true') {
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
} else {
    error_reporting(0);
    ini_set('display_errors', '0');
}

// Timezone
date_default_timezone_set($_ENV['APP_TIMEZONE'] ?? 'UTC');

// Security headers
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Permissions-Policy: geolocation=(), microphone=(), camera=()');

// CORS for API
if (str_starts_with($_SERVER['REQUEST_URI'] ?? '', '/api/')) {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    header('Content-Type: application/json; charset=utf-8');
    
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        http_response_code(204);
        exit;
    }
}

// Boot application
use App\Core\Application;
use App\Core\Router;

try {
    $router = new Router();
    require BASE_PATH . '/routes/web.php';
    require BASE_PATH . '/routes/api.php';
    
    $app = new Application($router);
    $app->run();
} catch (\Throwable $e) {
    if ($_ENV['APP_DEBUG'] === 'true') {
        http_response_code(500);
        echo "<pre>" . htmlspecialchars((string)$e) . "</pre>";
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Internal Server Error']);
    }
}

🔹 الملف 4: app/Core/Router.php

php

<?php
namespace App\Core;

class Router
{
    private array $routes = [];
    private array $middlewares = [];

    public function add(string $method, string $path, callable|array $handler, array $middleware = []): void
    {
        $this->routes[] = [
            'method' => strtoupper($method),
            'path' => $path,
            'handler' => $handler,
            'middleware' => $middleware,
        ];
    }

    public function get(string $path, callable|array $handler, array $mw = []): void
    {
        $this->add('GET', $path, $handler, $mw);
    }

    public function post(string $path, callable|array $handler, array $mw = []): void
    {
        $this->add('POST', $path, $handler, $mw);
    }

    public function dispatch(string $method, string $uri): void
    {
        $uri = parse_url($uri, PHP_URL_PATH);
        $uri = rtrim($uri, '/') ?: '/';

        foreach ($this->routes as $route) {
            if ($route['method'] !== $method) continue;
            
            $pattern = preg_replace('#\{([a-z_]+)\}#i', '(?P<$1>[^/]+)', $route['path']);
            $pattern = '#^' . $pattern . '$#';

            if (preg_match($pattern, $uri, $matches)) {
                // Run middleware
                foreach ($route['middleware'] as $mw) {
                    $mwInstance = new $mw();
                    if (!$mwInstance->handle()) {
                        return;
                    }
                }

                // Extract params
                $params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);

                // Call handler
                $handler = $route['handler'];
                if (is_array($handler)) {
                    [$class, $method] = $handler;
                    $instance = new $class();
                    echo $instance->$method(...array_values($params));
                } else {
                    echo $handler(...array_values($params));
                }
                return;
            }
        }

        http_response_code(404);
        echo json_encode(['error' => 'Route not found', 'path' => $uri]);
    }
}

🔹 الملف 5: app/Core/Database.php

php

<?php
namespace App\Core;

use PDO;
use PDOException;

class Database
{
    private static ?PDO $instance = null;

    public static function connection(): PDO
    {
        if (self::$instance === null) {
            $dsn = sprintf(
                'mysql:host=%s;port=%s;dbname=%s;charset=%s',
                $_ENV['DB_HOST'],
                $_ENV['DB_PORT'] ?? 3306,
                $_ENV['DB_NAME'],
                $_ENV['DB_CHARSET'] ?? 'utf8mb4'
            );

            try {
                self::$instance = new PDO($dsn, $_ENV['DB_USER'], $_ENV['DB_PASS'], [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false,
                    PDO::ATTR_PERSISTENT => true,
                    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
                ]);
            } catch (PDOException $e) {
                throw new \RuntimeException('DB connection failed: ' . $e->getMessage());
            }
        }

        return self::$instance;
    }

    public static function query(string $sql, array $params = []): \PDOStatement
    {
        $stmt = self::connection()->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }

    public static function one(string $sql, array $params = []): ?array
    {
        $result = self::query($sql, $params)->fetch();
        return $result ?: null;
    }

    public static function all(string $sql, array $params = []): array
    {
        return self::query($sql, $params)->fetchAll();
    }

    public static function insert(string $table, array $data): int
    {
        $cols = implode(',', array_keys($data));
        $placeholders = implode(',', array_fill(0, count($data), '?'));
        $sql = "INSERT INTO $table ($cols) VALUES ($placeholders)";
        self::query($sql, array_values($data));
        return (int) self::connection()->lastInsertId();
    }

    public static function update(string $table, array $data, string $where, array $whereParams = []): int
    {
        $set = implode(',', array_map(fn($k) => "$k = ?", array_keys($data)));
        $sql = "UPDATE $table SET $set WHERE $where";
        return self::query($sql, [...array_values($data), ...$whereParams])->rowCount();
    }
}

🔹 الملف 6: app/Core/Auth.php — JWT كامل

php

<?php
namespace App\Core;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class Auth
{
    public static function generateToken(int $userId, string $email, string $role = 'user'): string
    {
        $payload = [
            'iss' => $_ENV['APP_URL'],
            'iat' => time(),
            'exp' => time() + (int)($_ENV['JWT_TTL'] ?? 86400),
            'sub' => $userId,
            'email' => $email,
            'role' => $role,
        ];

        return JWT::encode($payload, $_ENV['JWT_SECRET'], 'HS256');
    }

    public static function verify(string $token): ?array
    {
        try {
            $decoded = JWT::decode($token, new Key($_ENV['JWT_SECRET'], 'HS256'));
            return (array) $decoded;
        } catch (\Throwable $e) {
            return null;
        }
    }

    public static function currentUser(): ?array
    {
        $header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        
        if (!preg_match('/Bearer\s+(.+)/', $header, $m)) {
            return null;
        }

        $payload = self::verify($m[1]);
        if (!$payload) return null;

        return Database::one(
            'SELECT id, name, email, role, credits FROM users WHERE id = ?',
            [$payload['sub']]
        );
    }

    public static function require(): array
    {
        $user = self::currentUser();
        if (!$user) {
            http_response_code(401);
            echo json_encode(['error' => 'Unauthorized']);
            exit;
        }
        return $user;
    }

    public static function hashPassword(string $password): string
    {
        return password_hash($password, PASSWORD_ARGON2ID, [
            'memory_cost' => 65536,
            'time_cost' => 4,
            'threads' => 3,
        ]);
    }

    public static function verifyPassword(string $password, string $hash): bool
    {
        return password_verify($password, $hash);
    }
}

🔹 الملف 7: app/Controllers/ChatController.php

php

<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Database;
use App\Services\ProviderFactory;

class ChatController
{
    public function send(): string
    {
        $user = Auth::require();
        $input = json_decode(file_get_contents('php://input'), true);

        // Validation
        $message = trim($input['message'] ?? '');
        $conversationId = (int)($input['conversation_id'] ?? 0);
        $provider = $input['provider'] ?? 'openai';

        if (empty($message)) {
            http_response_code(422);
            return json_encode(['error' => 'Message is required']);
        }

        if (strlen($message) > 8000) {
            http_response_code(422);
            return json_encode(['error' => 'Message too long (max 8000 chars)']);
        }

        // Check credits
        if ($user['credits'] <= 0) {
            http_response_code(402);
            return json_encode(['error' => 'Insufficient credits']);
        }

        // Get or create conversation
        if ($conversationId === 0) {
            $conversationId = Database::insert('conversations', [
                'user_id' => $user['id'],
                'title' => mb_substr($message, 0, 60),
                'provider' => $provider,
            ]);
        }

        // Save user message
        Database::insert('messages', [
            'conversation_id' => $conversationId,
            'role' => 'user',
            'content' => $message,
        ]);

        // Build context (last 20 messages)
        $history = Database::all(
            'SELECT role, content FROM messages 
             WHERE conversation_id = ? 
             ORDER BY id DESC LIMIT 20',
            [$conversationId]
        );
        $history = array_reverse($history);

        // Call AI provider
        try {
            $ai = ProviderFactory::make($provider);
            $response = $ai->chat($history);
            
            $assistantMessage = $response['choices'][0]['message']['content'] 
                ?? $response['content'][0]['text'] 
                ?? 'No response';
            
            $tokens = $response['usage']['total_tokens'] ?? 0;
        } catch (\Throwable $e) {
            http_response_code(500);
            return json_encode(['error' => 'AI provider error: ' . $e->getMessage()]);
        }

        // Save assistant message
        Database::insert('messages', [
            'conversation_id' => $conversationId,
            'role' => 'assistant',
            'content' => $assistantMessage,
            'tokens' => $tokens,
        ]);

        // Deduct credits
        Database::update('users', 
            ['credits' => $user['credits'] - 1], 
            'id = ?', 
            [$user['id']]
        );

        // Log usage
        Database::insert('usage_logs', [
            'user_id' => $user['id'],
            'endpoint' => '/api/chat/send',
            'tokens' => $tokens,
            'cost' => $tokens * 0.000002,
            'ip' => $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0',
        ]);

        return json_encode([
            'success' => true,
            'conversation_id' => $conversationId,
            'message' => $assistantMessage,
            'tokens' => $tokens,
            'credits_remaining' => $user['credits'] - 1,
        ]);
    }

    public function list(): string
    {
        $user = Auth::require();
        $conversations = Database::all(
            'SELECT c.id, c.title, c.provider, c.created_at,
                    (SELECT COUNT(*) FROM messages WHERE conversation_id = c.id) as msg_count
             FROM conversations c 
             WHERE c.user_id = ? 
             ORDER BY c.id DESC LIMIT 100',
            [$user['id']]
        );
        return json_encode(['conversations' => $conversations]);
    }

    public function create(): string
    {
        $user = Auth::require();
        $input = json_decode(file_get_contents('php://input'), true);
        
        $id = Database::insert('conversations', [
            'user_id' => $user['id'],
            'title' => $input['title'] ?? 'New Chat',
            'provider' => $input['provider'] ?? 'openai',
        ]);

        return json_encode(['id' => $id, 'success' => true]);
    }

    public function delete(int $id): string
    {
        $user = Auth::require();
        Database::query(
            'DELETE FROM conversations WHERE id = ? AND user_id = ?',
            [$id, $user['id']]
        );
        return json_encode(['success' => true]);
    }
}

🔹 الملف 8: app/Controllers/ApiController.php — Auth

php

<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Database;

class ApiController
{
    public function register(): string
    {
        $input = json_decode(file_get_contents('php://input'), true);

        $name = trim($input['name'] ?? '');
        $email = filter_var($input['email'] ?? '', FILTER_VALIDATE_EMAIL);
        $password = $input['password'] ?? '';

        if (!$name || !$email || strlen($password) < 8) {
            http_response_code(422);
            return json_encode(['error' => 'بيانات غير صحيحة. كلمة المرور 8 أحرف على الأقل.']);
        }

        // Check if email exists
        $existing = Database::one('SELECT id FROM users WHERE email = ?', [$email]);
        if ($existing) {
            http_response_code(409);
            return json_encode(['error' => 'البريد مستخدم مسبقاً']);
        }

        $userId = Database::insert('users', [
            'name' => $name,
            'email' => $email,
            'password_hash' => Auth::hashPassword($password),
            'role' => 'user',
            'credits' => 100,
            'api_token' => bin2hex(random_bytes(32)),
        ]);

        $token = Auth::generateToken($userId, $email, 'user');

        return json_encode([
            'success' => true,
            'token' => $token,
            'user' => [
                'id' => $userId,
                'name' => $name,
                'email' => $email,
                'credits' => 100,
            ],
        ]);
    }

    public function login(): string
    {
        $input = json_decode(file_get_contents('php://input'), true);
        $email = filter_var($input['email'] ?? '', FILTER_VALIDATE_EMAIL);
        $password = $input['password'] ?? '';

        if (!$email || !$password) {
            http_response_code(422);
            return json_encode(['error' => 'البريد وكلمة المرور مطلوبان']);
        }

        $user = Database::one('SELECT * FROM users WHERE email = ?', [$email]);

        if (!$user || !Auth::verifyPassword($password, $user['password_hash'])) {
            http_response_code(401);
            return json_encode(['error' => 'بيانات الدخول غير صحيحة']);
        }

        $token = Auth::generateToken((int)$user['id'], $user['email'], $user['role']);

        return json_encode([
            'success' => true,
            'token' => $token,
            'user' => [
                'id' => (int)$user['id'],
                'name' => $user['name'],
                'email' => $user['email'],
                'role' => $user['role'],
                'credits' => (int)$user['credits'],
            ],
        ]);
    }

    public function me(): string
    {
        $user = Auth::require();
        return json_encode(['user' => $user]);
    }
}

🔹 الملف 9: app/Middleware/RateLimitMiddleware.php

php

<?php
namespace App\Middleware;

use App\Core\Database;

class RateLimitMiddleware
{
    public function handle(): bool
    {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
        $limit = (int)($_ENV['RATE_LIMIT_PER_MINUTE'] ?? 60);
        $key = "rate:$ip:" . floor(time() / 60);

        $file = sys_get_temp_dir() . '/' . md5($key) . '.ratelimit';
        
        $count = 0;
        if (file_exists($file)) {
            $data = json_decode(file_get_contents($file), true);
            if ($data['minute'] === floor(time() / 60)) {
                $count = $data['count'];
            }
        }

        if ($count >= $limit) {
            http_response_code(429);
            header('Retry-After: ' . (60 - (time() % 60)));
            echo json_encode(['error' => 'Too many requests. Please slow down.']);
            return false;
        }

        file_put_contents($file, json_encode([
            'minute' => floor(time() / 60),
            'count' => $count + 1,
        ]));

        return true;
    }
}

🔹 الملف 10: routes/api.php

php

<?php
use App\Controllers\ApiController;
use App\Controllers\ChatController;
use App\Middleware\RateLimitMiddleware;

/** @var \App\Core\Router $router */

// ═══ Public Routes ═══
$router->post('/api/auth/register', [ApiController::class, 'register'], [RateLimitMiddleware::class]);
$router->post('/api/auth/login', [ApiController::class, 'login'], [RateLimitMiddleware::class]);

// ═══ Protected Routes ═══
$router->get('/api/user/me', [ApiController::class, 'me']);

$router->get('/api/conversations', [ChatController::class, 'list']);
$router->post('/api/conversations', [ChatController::class, 'create']);
$router->delete('/api/conversations/{id}', [ChatController::class, 'delete']);

$router->post('/api/chat/send', [ChatController::class, 'send']);

// Health check
$router->get('/api/health', fn() => json_encode([
    'status' => 'ok',
    'version' => '1.0.0',
    'timestamp' => time(),
]));

🔹 الملف 11: الواجهة الأمامية — public/index.html

html

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Zezo AI — منصة الذكاء الاصطناعي</title>
    <meta name="description" content="منصة Zezo AI - دردشة ذكية متعددة النماذج">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <style>
        :root { --zezo-primary: #6366f1; }
        body { font-family: 'Segoe UI', Tahoma, sans-serif; }
        .chat-scroll { scrollbar-width: thin; }
        .chat-scroll::-webkit-scrollbar { width: 6px; }
        .chat-scroll::-webkit-scrollbar-thumb { background: #475569; border-radius: 3px; }
        .typing::after { content: '...'; animation: dots 1.5s infinite; }
        @keyframes dots {
            0%, 20% { content: '.'; }
            40% { content: '..'; }
            60%, 100% { content: '...'; }
        }
        .message-enter { animation: slideIn 0.3s ease; }
        @keyframes slideIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body class="bg-slate-900 text-slate-100 min-h-screen">

    <!-- Auth Screen -->
    <div id="authScreen" class="flex items-center justify-center min-h-screen p-4">
        <div class="w-full max-w-md bg-slate-800 rounded-2xl p-8 shadow-2xl">
            <h1 class="text-3xl font-bold mb-2 text-center bg-gradient-to-r from-indigo-400 to-purple-400 bg-clip-text text-transparent">
                Zezo AI
            </h1>
            <p class="text-slate-400 text-center mb-8">منصة الذكاء الاصطناعي المتعددة</p>

            <div class="flex gap-2 mb-6">
                <button onclick="switchTab('login')" id="tab-login"
                    class="flex-1 py-2 rounded-lg bg-indigo-600 font-medium">دخول</button>
                <button onclick="switchTab('register')" id="tab-register"
                    class="flex-1 py-2 rounded-lg bg-slate-700 font-medium">تسجيل</button>
            </div>

            <!-- Login Form -->
            <form id="loginForm" onsubmit="handleLogin(event)" class="space-y-4">
                <input type="email" id="loginEmail" placeholder="البريد الإلكتروني" required
                    class="w-full px-4 py-3 rounded-lg bg-slate-700 border border-slate-600 focus:border-indigo-500 focus:outline-none">
                <input type="password" id="loginPassword" placeholder="كلمة المرور" required
                    class="w-full px-4 py-3 rounded-lg bg-slate-700 border border-slate-600 focus:border-indigo-500 focus:outline-none">
                <button type="submit"
                    class="w-full py-3 rounded-lg bg-indigo-600 hover:bg-indigo-700 font-bold transition">
                    تسجيل الدخول
                </button>
            </form>

            <!-- Register Form -->
            <form id="registerForm" onsubmit="handleRegister(event)" class="space-y-4 hidden">
                <input type="text" id="regName" placeholder="الاسم الكامل" required
                    class="w-full px-4 py-3 rounded-lg bg-slate-700 border border-slate-600 focus:border-indigo-500 focus:outline-none">
                <input type="email" id="regEmail" placeholder="البريد الإلكتروني" required
                    class="w-full px-4 py-3 rounded-lg bg-slate-700 border border-slate-600 focus:border-indigo-500 focus:outline-none">
                <input type="password" id="regPassword" placeholder="كلمة المرور (8+ أحرف)" required minlength="8"
                    class="w-full px-4 py-3 rounded-lg bg-slate-700 border border-slate-600 focus:border-indigo-500 focus:outline-none">
                <button type="submit"
                    class="w-full py-3 rounded-lg bg-indigo-600 hover:bg-indigo-700 font-bold transition">
                    إنشاء حساب
                </button>
            </form>

            <p id="authError" class="text-red-400 text-sm mt-4 text-center hidden"></p>
        </div>
    </div>

    <!-- Chat Screen -->
    <div id="chatScreen" class="hidden h-screen flex flex-col">
        <!-- Header -->
        <header class="bg-slate-800 border-b border-slate-700 px-4 py-3 flex items-center justify-between">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-full bg-gradient-to-r from-indigo-500 to-purple-500 flex items-center justify-center font-bold">Z</div>
                <div>
                    <h2 class="font-bold">Zezo AI</h2>
                    <p class="text-xs text-slate-400" id="userCredits">جاري التحميل...</p>
                </div>
            </div>
            <div class="flex items-center gap-2">
                <select id="providerSelect" onchange="changeProvider()"
                    class="bg-slate-700 border border-slate-600 rounded-lg px-3 py-2 text-sm">
                    <option value="openai">GPT-4o</option>
                    <option value="claude">Claude 3.5</option>
                    <option value="gemini">Gemini 1.5</option>
                </select>
                <button onclick="logout()" class="px-3 py-2 rounded-lg bg-red-600/20 text-red-400 text-sm hover:bg-red-600/30">
                    خروج
                </button>
            </div>
        </header>

        <!-- Messages -->
        <main id="messages" class="flex-1 overflow-y-auto chat-scroll p-4 space-y-4">
            <div class="text-center text-slate-500 py-12">
                <div class="text-4xl mb-3">✨</div>
                <p class="text-lg font-medium">مرحباً بك في Zezo AI</p>
                <p class="text-sm">ابدأ محادثتك الآن مع أقوى نماذج الذكاء الاصطناعي</p>
            </div>
        </main>

        <!-- Input -->
        <footer class="bg-slate-800 border-t border-slate-700 p-4">
            <div class="flex gap-2 max-w-4xl mx-auto">
                <textarea id="userInput" rows="1" placeholder="اكتب رسالتك..."
                    onkeydown="handleKey(event)"
                    oninput="autoResize(this)"
                    class="flex-1 px-4 py-3 rounded-xl bg-slate-700 border border-slate-600 focus:border-indigo-500 focus:outline-none resize-none max-h-40"></textarea>
                <button onclick="sendMessage()" id="sendBtn"
                    class="px-6 py-3 rounded-xl bg-indigo-600 hover:bg-indigo-700 font-bold transition disabled:opacity-50">
                    إرسال
                </button>
            </div>
        </footer>
    </div>

<script>
// ═══════════════════════════════════════════════
// Zezo AI Platform — Frontend Logic
// ═══════════════════════════════════════════════

const API = '/api';
let state = {
    token: localStorage.getItem('zezo_token'),
    user: null,
    conversationId: 0,
    provider: 'openai',
    sending: false,
};

// ═══ Init ═══
document.addEventListener('DOMContentLoaded', () => {
    if (state.token) {
        loadUser();
    }
});

// ═══ Auth ═══
function switchTab(tab) {
    document.getElementById('loginForm').classList.toggle('hidden', tab !== 'login');
    document.getElementById('registerForm').classList.toggle('hidden', tab !== 'register');
    document.getElementById('tab-login').className = tab === 'login'
        ? 'flex-1 py-2 rounded-lg bg-indigo-600 font-medium'
        : 'flex-1 py-2 rounded-lg bg-slate-700 font-medium';
    document.getElementById('tab-register').className = tab === 'register'
        ? 'flex-1 py-2 rounded-lg bg-indigo-600 font-medium'
        : 'flex-1 py-2 rounded-lg bg-slate-700 font-medium';
}

async function handleLogin(e) {
    e.preventDefault();
    const email = document.getElementById('loginEmail').value;
    const password = document.getElementById('loginPassword').value;
    await authRequest('/auth/login', { email, password });
}

async function handleRegister(e) {
    e.preventDefault();
    const name = document.getElementById('regName').value;
    const email = document.getElementById('regEmail').value;
    const password = document.getElementById('regPassword').value;
    await authRequest('/auth/register', { name, email, password });
}

async function authRequest(endpoint, body) {
    try {
        const res = await fetch(API + endpoint, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body),
        });
        const data = await res.json();
        
        if (!res.ok) throw new Error(data.error || 'خطأ في المصادقة');
        
        state.token = data.token;
        state.user = data.user;
        localStorage.setItem('zezo_token', data.token);
        
        showChatScreen();
    } catch (err) {
        const errEl = document.getElementById('authError');
        errEl.textContent = err.message;
        errEl.classList.remove('hidden');
    }
}

async function loadUser() {
    try {
        const res = await fetch(API + '/user/me', {
            headers: { 'Authorization': 'Bearer ' + state.token },
        });
        if (!res.ok) throw new Error('Session expired');
        const data = await res.json();
        state.user = data.user;
        showChatScreen();
    } catch {
        localStorage.removeItem('zezo_token');
        state.token = null;
    }
}

function logout() {
    localStorage.removeItem('zezo_token');
    state.token = null;
    state.user = null;
    state.conversationId = 0;
    location.reload();
}

function showChatScreen() {
    document.getElementById('authScreen').classList.add('hidden');
    document.getElementById('chatScreen').classList.remove('hidden');
    document.getElementById('userCredits').textContent = 
        `${state.user.name} • ${state.user.credits} نقطة`;
}

// ═══ Chat ═══
function handleKey(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
    }
}

function autoResize(el) {
    el.style.height = 'auto';
    el.style.height = Math.min(el.scrollHeight, 160) + 'px';
}

async function sendMessage() {
    if (state.sending) return;
    
    const input = document.getElementById('userInput');
    const message = input.value.trim();
    if (!message) return;

    state.sending = true;
    document.getElementById('sendBtn').disabled = true;
    input.value = '';
    input.style.height = 'auto';

    // Clear welcome message
    const messages = document.getElementById('messages');
    if (messages.querySelector('.text-center')) messages.innerHTML = '';

    appendMessage('user', message);
    const typingEl = appendTyping();

    try {
        const res = await fetch(API + '/chat/send', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + state.token,
            },
            body: JSON.stringify({
                message,
                conversation_id: state.conversationId,
                provider: state.provider,
            }),
        });

        const data = await res.json();
        typingEl.remove();

        if (!res.ok) throw new Error(data.error || 'فشل الاتصال');

        state.conversationId = data.conversation_id;
        state.user.credits = data.credits_remaining;
        document.getElementById('userCredits').textContent = 
            `${state.user.name} • ${state.user.credits} نقطة`;

        appendMessage('assistant', data.message);
    } catch (err) {
        typingEl.remove();
        appendMessage('error', '⚠️ ' + err.message);
    } finally {
        state.sending = false;
        document.getElementById('sendBtn').disabled = false;
    }
}

function appendMessage(role, content) {
    const messages = document.getElementById('messages');
    const div = document.createElement('div');
    div.className = 'message-enter flex gap-3 ' + (role === 'user' ? 'flex-row-reverse' : '');

    const avatar = role === 'user'
        ? '<div class="w-8 h-8 rounded-full bg-indigo-600 flex items-center justify-center text-sm font-bold shrink-0">أنا</div>'
        : role === 'error'
            ? '<div class="w-8 h-8 rounded-full bg-red-600 flex items-center justify-center shrink-0">!</div>'
            : '<div class="w-8 h-8 rounded-full bg-gradient-to-r from-indigo-500 to-purple-500 flex items-center justify-center text-sm font-bold shrink-0">Z</div>';

    const bubbleClass = role === 'user'
        ? 'bg-indigo-600 rounded-br-none'
        : role === 'error'
            ? 'bg-red-600/20 border border-red-600/40 rounded-bl-none'
            : 'bg-slate-700 rounded-bl-none';

    const rendered = role === 'assistant' ? marked.parse(content) : escapeHtml(content);

    div.innerHTML = `
        ${avatar}
        <div class="max-w-[80%] px-4 py-3 rounded-2xl ${bubbleClass} prose prose-invert prose-sm">
            ${rendered}
        </div>
    `;
    messages.appendChild(div);
    messages.scrollTop = messages.scrollHeight;
    return div;
}

function appendTyping() {
    const messages = document.getElementById('messages');
    const div = document.createElement('div');
    div.className = 'flex gap-3';
    div.innerHTML = `
        <div class="w-8 h-8 rounded-full bg-gradient-to-r from-indigo-500 to-purple-500 flex items-center justify-center text-sm font-bold shrink-0">Z</div>
        <div class="px-4 py-3 rounded-2xl rounded-bl-none bg-slate-700">
            <span class="typing text-slate-400"></span>
        </div>
    `;
    messages.appendChild(div);
    messages.scrollTop = messages.scrollHeight;
    return div;
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function changeProvider() {
    state.provider = document.getElementById('providerSelect').value;
    state.conversationId = 0;
}
</script>
</body>
</html>

🔹 الملف 12: database/migrations/001_initial.sql

sql

-- ═══════════════════════════════════════════════
-- Zezo AI Platform — Initial Migration
-- Run: mysql -u user -p db < 001_initial.sql
-- ═══════════════════════════════════════════════

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- Users
CREATE TABLE IF NOT EXISTS users (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(191) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    role ENUM('user','pro','admin') DEFAULT 'user',
    credits INT DEFAULT 100,
    api_token VARCHAR(64) UNIQUE,
    email_verified_at TIMESTAMP NULL,
    last_login_at TIMESTAMP NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Conversations
CREATE TABLE IF NOT EXISTS conversations (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    title VARCHAR(255),
    provider ENUM('openai','claude','gemini','deepseek','groq') DEFAULT 'openai',
    model VARCHAR(50) DEFAULT 'gpt-4o-mini',
    tokens_used INT DEFAULT 0,
    is_archived BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_user_active (user_id, is_archived)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Messages
CREATE TABLE IF NOT EXISTS messages (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    conversation_id BIGINT UNSIGNED NOT NULL,
    role ENUM('system','user','assistant') NOT NULL,
    content LONGTEXT NOT NULL,
    tokens INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (conversation_id) REFERENCES conversations(id) ON DELETE CASCADE,
    INDEX idx_conv_date (conversation_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- API Keys Vault
CREATE TABLE IF NOT EXISTS api_keys_vault (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    provider VARCHAR(50) NOT NULL,
    encrypted_key TEXT NOT NULL,
    label VARCHAR(100),
    is_active BOOLEAN DEFAULT TRUE,
    last_used_at TIMESTAMP NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Usage Logs
CREATE TABLE IF NOT EXISTS usage_logs (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    endpoint VARCHAR(100),
    tokens INT DEFAULT 0,
    cost DECIMAL(12,8) DEFAULT 0,
    ip VARCHAR(45),
    user_agent VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_user_date (user_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Transactions (Billing)
CREATE TABLE IF NOT EXISTS transactions (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    amount DECIMAL(10,2) NOT NULL,
    currency VARCHAR(3) DEFAULT 'USD',
    gateway VARCHAR(50),
    gateway_ref VARCHAR(255),
    status ENUM('pending','success','failed','refunded') DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- API Tokens for developers
CREATE TABLE IF NOT EXISTS developer_tokens (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    name VARCHAR(100),
    token_hash VARCHAR(64) UNIQUE NOT NULL,
    scopes JSON,
    rate_limit INT DEFAULT 100,
    last_used_at TIMESTAMP NULL,
    expires_at TIMESTAMP NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Seed admin
INSERT INTO users (name, email, password_hash, role, credits)
VALUES ('Zezo Admin', 'admin@zezoai.twisttaste.com', 
        '$argon2id$v=19$m=65536,t=4,p=3$...', 'admin', 999999)
ON DUPLICATE KEY UPDATE name = VALUES(name);

SET FOREIGN_KEY_CHECKS = 1;

🎬 القسم 25: خطوات التنفيذ الفورية (Copy-Paste Ready)

bash

# ═══════════════════════════════════════════════
# STEP 1: على الهاتف (Termux)
# ═══════════════════════════════════════════════
cd ~
mkdir zezo-ai-platform && cd zezo-ai-platform

# Clone fork موجود أو ابدأ من الصفر
git init
git remote add origin git@github.com:Zezo-Ai/zezo-ai-platform.git

# ═══════════════════════════════════════════════
# STEP 2: على Hostinger hPanel
# ═══════════════════════════════════════════════
# 1. Domains → Subdomains → Add:
#    app.zezoai.twisttaste.com
# 2. Files → Git → Connect to GitHub
# 3. Advanced → PHP Configuration → PHP 8.2
# 4. Databases → MySQL → Create zezo_ai_db
# 5. SSL → Let's Encrypt → Enable

# ═══════════════════════════════════════════════
# STEP 3: من Terminal الاستضافة (SSH)
# ═══════════════════════════════════════════════
ssh u123456789@your-hostinger-server

cd ~/domains/app.zezoai.twisttaste.com/public_html
git clone git@github.com:Zezo-Ai/zezo-ai-platform.git .

composer install --no-dev --optimize-autoloader
cp .env.example .env
nano .env    # املأ القيم

# Import database
mysql -u zezo_user -p zezo_ai_db < database/migrations/001_initial.sql

# Permissions
chmod -R 755 storage
chmod -R 755 public

# ═══════════════════════════════════════════════
# STEP 4: اختبار
# ═══════════════════════════════════════════════
curl https://app.zezoai.twisttaste.com/api/health
# Expected: {"status":"ok","version":"1.0.0","timestamp":...}

🧪 القسم 26: اختبار API كامل (من الهاتف)

bash

# 1. تسجيل مستخدم جديد
curl -X POST https://app.zezoai.twisttaste.com/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{"name":"Zezo","email":"test@zezo.ai","password":"StrongPass123"}'

# Response:
# {"success":true,"token":"eyJhbG...","user":{"id":1,...}}

# 2. استخرج التوكن
TOKEN="eyJhbG..."

# 3. أرسل رسالة
curl -X POST https://app.zezoai.twisttaste.com/api/chat/send \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"message":"اشرح لي الذكاء الاصطناعي ببساطة","provider":"openai"}'

# 4. اعرض المحادثات
curl https://app.zezoai.twisttaste.com/api/conversations \
  -H "Authorization: Bearer $TOKEN"

📊 القسم 27: لوحة المراقبة (Monitoring Dashboard)

php

// app/Controllers/AdminController.php
<?php
namespace App\Controllers;

use App\Core\Database;
use App\Core\Auth;

class AdminController
{
    public function stats(): string
    {
        $user = Auth::require();
        if ($user['role'] !== 'admin') {
            http_response_code(403);
            return json_encode(['error' => 'Forbidden']);
        }

        $stats = [
            'users' => [
                'total' => Database::one('SELECT COUNT(*) as c FROM users')['c'],
                'today' => Database::one('SELECT COUNT(*) as c FROM users WHERE DATE(created_at) = CURDATE()')['c'],
                'pro' => Database::one("SELECT COUNT(*) as c FROM users WHERE role IN ('pro','admin')")['c'],
            ],
            'conversations' => [
                'total' => Database::one('SELECT COUNT(*) as c FROM conversations')['c'],
                'today' => Database::one('SELECT COUNT(*) as c FROM conversations WHERE DATE(created_at) = CURDATE()')['c'],
            ],
            'messages' => [
                'total' => Database::one('SELECT COUNT(*) as c FROM messages')['c'],
                'today' => Database::one('SELECT COUNT(*) as c FROM messages WHERE DATE(created_at) = CURDATE()')['c'],
            ],
            'tokens' => [
                'total' => Database::one('SELECT COALESCE(SUM(tokens),0) as t FROM messages')['t'],
                'today' => Database::one('SELECT COALESCE(SUM(tokens),0) as t FROM messages WHERE DATE(created_at) = CURDATE()')['t'],
            ],
            'revenue' => [
                'total' => Database::one("SELECT COALESCE(SUM(amount),0) as s FROM transactions WHERE status = 'success'")['s'],
                'month' => Database::one("SELECT COALESCE(SUM(amount),0) as s FROM transactions WHERE status = 'success' AND MONTH(created_at) = MONTH(CURDATE())")['s'],
            ],
        ];

        return json_encode($stats);
    }

    public function recentUsers(): string
    {
        $user = Auth::require();
        if ($user['role'] !== 'admin') return json_encode(['error' => 'Forbidden']);

        $users = Database::all(
            'SELECT id, name, email, role, credits, created_at 
             FROM users ORDER BY id DESC LIMIT 50'
        );

        return json_encode(['users' => $users]);
    }
}

🔐 القسم 28: تحسينات أمنية إضافية

🔸 قالب app/Middleware/AdminMiddleware.php

php

<?php
namespace App\Middleware;

use App\Core\Auth;

class AdminMiddleware
{
    public function handle(): bool
    {
        $user = Auth::currentUser();
        if (!$user || $user['role'] !== 'admin') {
            http_response_code(403);
            echo json_encode(['error' => 'Admin access required']);
            return false;
        }
        return true;
    }
}

🔸 حماية CSRF للـ Forms التقليدية

php

// app/Helpers/Csrf.php
<?php
namespace App\Helpers;

class Csrf
{
    public static function token(): string
    {
        if (session_status() === PHP_SESSION_NONE) session_start();
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['csrf_token'];
    }

    public static function verify(string $token): bool
    {
        if (session_status() === PHP_SESSION_NONE) session_start();
        return hash_equals($_SESSION['csrf_token'] ?? '', $token);
    }
}

🎨 القسم 29: تحسين الواجهة — Themes

javascript

// أضف داخل <script> لتبديل الثيم
const themes = {
    dark: { bg: 'bg-slate-900', text: 'text-slate-100', card: 'bg-slate-800' },
    light: { bg: 'bg-slate-50', text: 'text-slate-900', card: 'bg-white' },
    purple: { bg: 'bg-purple-900', text: 'text-purple-50', card: 'bg-purple-800' },
};

function setTheme(name) {
    const theme = themes[name];
    document.body.className = `${theme.bg} ${theme.text} min-h-screen`;
    localStorage.setItem('zezo_theme', name);
}

🚀 القسم 30: أوامر النشر السريعة

🔸 سكربت النشر deploy.sh

bash

#!/bin/bash
# ═══════════════════════════════════════════════
# Zezo AI — One-Click Deploy Script
# ═══════════════════════════════════════════════

set -e

echo "🚀 Deploying Zezo AI Platform..."
echo "📍 Target: app.zezoai.twisttaste.com"

# 1. Pull latest
echo "📥 Pulling latest code..."
git pull origin main

# 2. Composer
echo "📦 Installing dependencies..."
composer install --no-dev --optimize-autoloader --no-interaction

# 3. Migrations (اختياري)
# php migrate.php

# 4. Clear caches
echo "🧹 Clearing caches..."
rm -rf storage/cache/*

# 5. Permissions
echo "🔐 Fixing permissions..."
chmod -R 755 storage
chmod -R 644 storage/logs/*.log 2>/dev/null || true

# 6. Restart services (إذا متوفر)
# systemctl reload php8.2-fpm

echo "✅ Deployment complete!"
echo "🌐 https://app.zezoai.twisttaste.com"

جعل السكربت قابل للتنفيذ:

bash

chmod +x deploy.sh
./deploy.sh

📋 القسم 31: قائمة المراجعة النهائية (Final Checklist)

markdown

## ✅ قبل الإطلاق

### البنية التحتية
- [ ] Subdomain app.zezoai.twisttaste.com يعمل
- [ ] SSL شهادة فعالة (Let's Encrypt)
- [ ] DNS Records صحيحة (A + CNAME)
- [ ] PHP 8.2+ مثبت
- [ ] MySQL database منشأة
- [ ] Git integration مفعل

### الأمان
- [ ] .env محمي (خارج public)
- [ ] .htaccess يمنع الوصول لـ .env
- [ ] HTTPS إجباري
- [ ] Rate limiting مفعل
- [ ] 2FA على حساب Hostinger
- [ ] SSH keys بدل passwords
- [ ] Backups يومية تلقائية

### الكود
- [ ] composer install ناجح
- [ ] Migrations مطبقة
- [ ] API /health يرد 200
- [ ] Register/Login يعملان
- [ ] Chat يعمل مع 3 providers
- [ ] Logs تُكتب في storage/logs
- [ ] لا توجد أخطاء PHP

### التسويق
- [ ] Landing page جاهزة
- [ ] SEO meta tags
- [ ] Open Graph images
- [ ] Google Analytics
- [ ] Sitemap.xml
- [ ] robots.txt

### المراقبة
- [ ] UptimeRobot config
- [ ] Sentry DSN مفعل
- [ ] Email alerts
- [ ] Log rotation

🎁 القسم 32: الخطوة التالية — اختر مسارك

الآن معك 32 قسماً كاملاً من البنية والحزمة التقنية. اختر ما تريد أن أنفذه بعمق:

🎯 المسارات المتقدمة المتاحة

#المسارالوصفالعمق
1🎨 Frontend Proواجهة Vue 3 كاملة + Pinia + Routerمتقدم
2💳 Billing SystemStripe + Credits + Invoices + Webhooksمتقدم
3📱 PWA + Mobileتحويل الواجهة لتطبيق يعمل offlineمتوسط
4🤖 Multi-Provider Routerذكاء في اختيار المزود + Fallback + Cost Optimizationمتقدم
5📊 Admin Dashboardلوحة تحكم كاملة مع Charts + Users + Revenueمتوسط
6🔌 Public API + SDKsAPI للمطورين + مكتبات PHP/Python/JSمتقدم
7🌊 Streaming ResponsesSSE/WebSocket للردود الفوريةمتقدم
8🎨 RAG Systemرفع ملفات + Vector DB + بحث دلاليخبير
9🎭 AI Agentsوكلاء ذكيون بأدوات (Tools + Functions)خبير
10🌍 Multi-Languageدعم كامل عربي/إنجليزي/فرنسيمتوسط

💬 قل رقم واحد وسأبني لك:

مثال على ما ستحصل عليه عند اختيار رقم 3 (PWA):

  • manifest.json كامل
  • service-worker.js مع caching strategies
  • Install prompt مخصص
  • Offline fallback page
  • Push notifications setup
  • App icons generator

مثال على رقم 2 (Billing):

  • Stripe checkout كامل
  • Webhook handler مع signature verification
  • Credits top-up logic
  • Pricing table UI
  • Invoices PDF generator
  • Subscription management

🚀 جاهز؟ اختر رقم من الجدول أعلاه وستحصل على حزمة كود كاملة جاهزة للنسخ في الرد التالي — مع شروحات مفصلة، واختبار، وخطوات نشر على استضافتك.

هذا الرد تم إنشاؤه بواسطة AI، وهو للإشارة فقط.

أدخل سؤالك

Scroll to Top