grthtrhthjhtyjytjytkergtrhtrjytjerhrfh# 🚀 Complete cPanel Deployment & Production Guide

This guide ensures a seamless, production-ready migration of the **BrightBrains Electronics Shop ERP** to direct cPanel environments, mapped as requested under:
- **cPanel Path**: `/public_html/elestore`
- **Application URL**: `http://brightbrains.pk/elestore`
- **MySQL Database**: `brightbrai_electronics`

---

## 📅 Prerequisite Server Environment
Ensure your cPanel hosting account supports:
- **PHP**: Version 8.2 or 8.3 (Highly recommended)
- **Extensions**: `PDO_MySQL`, `BCMath`, `Ctype`, `Fileinfo`, `JSON`, `Mbstring`, `OpenSSL`, `XML`, `Tokenizer`
- **Database Engine**: MySQL 8.x or MariaDB 10.x
- **composer**: Standard Composer utility

---

## 🛠️ Step 1: Provision MySQL Database in cPanel
1. Log in to your **cPanel Dashboard**.
2. Navigate to **Databases** -> **MySQL Database Wizard**.
3. Create a new database named:
   - **Database Name**: `brightbrai_electronics`
4. Create a new user with secure credentials:
   - **Username**: `brightbrai_electronics`
   - **Password**: `Khaskheli123@`
5. Associate the user to the database and select **All Privileges** -> click **Make Changes**.

---

## 📦 Step 2: Preparing the Backend Configuration
Your `/laravel` directory is fully bootstrapped with pre-filled settings. 
Verify `/laravel/.env` holds the correct connection tags:
```env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_DATABASE=brightbrai_electronics
DB_USERNAME=brightbrai_electronics
DB_PASSWORD=Khaskheli123@
APP_URL=http://brightbrains.pk/elestore
```

---

## 💻 Step 3: Local Compilation & Building (Inertia.js + Vite)
Compile and bundle your assets locally ahead of uploading to cPanel to reduce build load on shared servers:
1. Navigate into the project folder on your machine:
   ```bash
   cd laravel
   ```
   *(Note: Ensure that the `bootstrap/cache` and `storage` directories are present. We have pre-created `.gitkeep` placeholder files inside them to preserve their structure. If they are ever deleted, or if you hit folder permission/missing errors, you can manually create the standard folder paths: `mkdir bootstrap\cache` and `mkdir storage\framework\cache\data storage\framework\sessions storage\framework\views storage\logs` on Windows, or `mkdir -p bootstrap/cache storage/framework/cache/data storage/framework/sessions storage/framework/views storage/logs` on macOS/Linux.)*
2. Build and download Composer PHP packages:
   ```bash
   composer install --no-dev --optimize-autoloader
   ```
   *(Note: We have preset `"policy.advisories.block": false` under `"config"` in `composer.json`. This automatically prevents Composer from blocking the installation on local security advisories. You can run the command cleanly as-is. If you are using an older Composer version that doesn't respect JSON-level policy exclusions, you can append `--no-security-blocking` to the installation command instead.)*
3. Initialize the application encryption key:
   ```bash
   php artisan key:generate
   ```
   *(Note: Since `APP_ENV` is configured as `production` in your `.env`, Laravel will display an warning prompt: `Are you sure you want to run this command?`. Simply type **`yes`** and press Enter, or run **`php artisan key:generate --force`** to bypass the interactive check.)*
4. Build the Inertia-compiles and frontend UI files:
   ```bash
   npm install
   npm run build
   ```
This populates the `public/build/` directory with production-ready asset indices.

---

## 📤 Step 4: Uploading directly to cPanel File Manager
For clean subfolder routing on cPanel without revealing the `/public` prefix in urls:

### Option A: Direct Subdirectory Upload (Traditional)
1. Zip the entire content of your compiled `laravel` folder.
2. Open the cPanel **File Manager** and navigate into `/public_html/elestore`.
3. Upload the Zip file here and extract it.
4. Ensure the `.htaccess` files generated under `/public_html/elestore` and `/public_html/elestore/public` are visible (enable "Show Hidden Files" in cPanel settings).
   - Our preflight `.htaccess` file inside `/laravel/.htaccess` dynamically routes non-public subdirectory queries direct to the web entrypoints.

### Option B: Root folder separation (Secure & Best-Practice ⭐)
1. Compress and upload all folder contents **except** the `public/` directory into a secure private folder *above* `public_html`, e.g., `/home/brightbrains/laravel-core`.
2. Extract the contents of the `public/` folder directly into `/public_html/elestore`.
3. Modify `/public_html/elestore/index.php` paths to find the autoloader. Edit lines ~34 and ~47 inside `/public_html/elestore/index.php`:
   ```php
   // Change from original paths to target home directories:
   require '/home/brightbrains/laravel-core/vendor/autoload.php';
   $app = require_once '/home/brightbrains/laravel-core/bootstrap/app.php';
   ```
This isolates critical logs and dotenv keys securely away from public accessibility!

---

## 🗄️ Step 5: Database Migrations & Seeding
Publish tables and load original records over your live server database:

- **Method A: 1-Click Web-Based Setup Wizard (EASIEST & RECOMMENDED) ⭐**
  We have built a fully automated installer interface directly into your application! You do not need SSH, cron setup, or command-line skills.
  1. Once you have uploaded the project files and configured your `.env` credentials, open your browser.
  2. Navigate to: **`https://electronic.brightbrains.pk/db-setup`** (or your directory route e.g. `http://brightbrains.pk/elestore/db-setup`)
  3. You will see the **BrightBrains Database Wizard** page:
     - It will automatically verify if your database credentials are correct. If it shows **Connected Successfully!** (in green), you are ready.
     - If it shows **Failed to Connect**, it will print the exact database error so you can fix your credentials in `.env`.
  4. Click the large button: **`Run Automatic Database Setup`**.
  5. The assistant will live-stream the background Artisan commands, executing all migrations and fully seeding the master data, setup parameters, categories, and test users.
  6. Once complete, the database will reload automatically, and your ERP will be completely primed for usage!

### 🛑 Troubleshooting "SQLSTATE[28000] [1045] Access denied" Error in cPanel
If you see the error: **`SQLSTATE[28000] [1045] Access denied for user 'brightbrai_electronics'@'localhost' (using password: YES)`**, it always means MySQL could not authorize your user. 

Follow these **3 quick steps** in cPanel to resolve it:

1. **Verify User is Added to Database (Crucial for cPanel) 🌟**:
   - In cPanel, navigate to **MySQL Databases**.
   - Scroll down to the **Add User To Database** section.
   - Select **User**: `brightbrai_electronics` and **Database**: `brightbrai_electronics` from the dropdowns.
   - Click the **Add** button.
   - On the next screen, tick the **ALL PRIVILEGES** checkbox at the top, and click **Make Changes**.
   - *Note: In cPanel, simply creating a database and user is not enough; they must be actively linked with full privileges.*

2. **Wrap your DB_PASSWORD in Double Quotes in `.env`**:
   - Open your `.env` file in the cPanel File Manager.
   - If your password contains special characters (like `@`, `#`, `!`), you **MUST** wrap it in double quotes:
     ```env
     DB_PASSWORD="Khaskheli123@"
     ```
   - Save the `.env` file.

3. **Check Host Name Matches**:
   - In your `.env` file, try setting:
     ```env
     DB_HOST=127.0.0.1
     ```
   - If that fails, change it to:
     ```env
     DB_HOST=localhost
     ```
   - Save the `.env` file.

---

- **Method B: via SSH Terminal**
  If your cPanel subscription enables SSH Access:
  ```bash
  cd /public_html/elestore
  php artisan migrate --force
  php artisan db:seed --force
  ```

- **Method C: Manual Database Import / Cron Task**
  If SSH terminal is restricted, you can load migrations using custom cron tasks:
  1. Go to **cPanel Cron Jobs**.
  2. Register a quick single-trigger command:
     ```bash
     /usr/local/bin/php /home/brightbrains/public_html/elestore/artisan migrate --seed --force
     ```
  3. Wait 1 minute for execution, check output email, then **Delete** the cron task.

---

## ⚠️ Troubleshooting Platform & PHP Version Mismatches
If you encounter a fatal error like:
> `Fatal error: Uncaught RuntimeException: Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 8.4.1". You are running 8.2.30.`

### Why it happens:
Your local machine is running PHP 8.4+, and when you ran `composer install`, Composer resolved packages targeting PHP 8.4 and compiled a platform check rule under `vendor/composer/platform_check.php` that requires PHP 8.4.1 on the server. Since your cPanel server runs PHP 8.2.30, it fails.

### How to resolve:
1. **Configured Platform Target**: We have updated your `/laravel/composer.json` to include:
   ```json
   "config": {
       "platform": {
           "php": "8.2.30"
       }
   }
   ```
2. **Re-generate Lock File**: Run this command on your machine inside the `laravel` directory:
   ```bash
   composer update --no-dev --optimize-autoloader --no-security-blocking
   ```
   *This forces Composer to fetch versions compatible with PHP 8.2.30 and configures the autoloader rules accordingly.*
3. **Re-upload to cPanel**: Re-upload the newly generated `vendor/` directory and `composer.lock` file to your server.

Alternatively, if you cannot re-run composer locally, you can disable the platform check entirely by setting `"platform-check": false` inside the `"config"` block of your `composer.json` OR run installation with `--ignore-platform-reqs`, but using the `platform` override tag (Step 1 above) is the most robust and standard solution.

---

## 🚫 Troubleshooting MIME-Type / Asset Loading Errors inside Subfolders
If you encounter a console error like:
> `Failed to load module script: Expected a JavaScript-or-Wasm module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced...`

### Why it happens:
Your Laravel application is hosted in a subdirectory (e.g., `http://brightbrains.pk/elestore/`). When the browser requests the compiled JS code from `http://brightbrains.pk/elestore/build/assets/app-CqFCdo_o.js`, cPanel's Apache rewrite rules inside the root `.htaccess` evaluate `RewriteCond %{REQUEST_URI} !^/public/`. 

Since the URI `/elestore/build/assets/...` does not begin with `/public/` (it begins with `/elestore/`), the condition passes and Apache keeps appending `public/` in an endless internal routing loop (e.g., `public/public/public/build/...`). This infinite loop causes the request to either fail or fallback to Laravel's main `index.php` front-router, which serves the HTML view instead of the raw JS code, triggering the "Expected a JavaScript-or-Wasm module but got text/html" MIME-type safety error.

### How to resolve (Recommended: Switch to Subdomain):
The cleanest, most foolproof, and standard way to host Laravel on cPanel is using a **Subdomain** (e.g., `https://electronic.brightbrains.pk`) instead of a subfolder. This completely bypasses any `.htaccess` rewrite loops and nested subdirectory problems.

#### Option 1: Deploy on a Subdomain (Highly Recommended 🌟)
1. **Create Subdomain in cPanel**: Go to **Domains** / **Subdomains** in cPanel and create `electronic.brightbrains.pk`.
2. **Set the Document Root**: Point the subdomain's **Document Root** directly to the Laravel `public` directory:
   ```text
   public_html/elestore/public
   ```
   *(Assuming your zip is extracted directly in `public_html/elestore`)*.
3. **No Root `.htaccess` Hack Required**: Since the subdomain points directly to `/public`, Apache serves the files natively without executing subfolder redirects.
4. **Update `.env`**: Open `public_html/elestore/.env` in your cPanel File Manager and configure:
   ```env
   APP_URL=https://electronic.brightbrains.pk
   ASSET_URL=https://electronic.brightbrains.pk
   ```

---

#### Option 2: Keep Subfolder and configured redirects
If you *must* keep it in a subfolder (`http://brightbrains.pk/elestore/`), apply these steps:

##### Part A: Update the Root `.htaccess`
We have modified your root `.htaccess` (`/laravel/.htaccess`) to include a subdirectory-safe wildcard condition:
```apache
    # Rewrite requests to public/ and prevent infinite routing loops in subdirectories
    RewriteCond %{REQUEST_URI} !^/public/
    RewriteCond %{REQUEST_URI} !/public/
    RewriteRule ^(.*)$ public/$1 [L]
```

##### Part B: Set `ASSET_URL` and `APP_URL` in your cPanel `.env` file
If you do not specify the subfolder in your environment variables, Laravel's `@vite` helper will generate absolute URLs resolving to the root domain (e.g. `http://brightbrains.pk/build/assets/app-CqFCdo_o.js`) instead of `http://brightbrains.pk/elestore/build/assets/...`. This bypasses your subdirectory entirely, hits your root website router, and gets returned as HTML (triggering the MIME-type error).

1. Log in to your cPanel File Manager and open the `.env` file located in `public_html/elestore/.env`.
2. Find (or add if missing) the following configuration variables:
   ```env
   APP_URL=https://brightbrains.pk/elestore
   ASSET_URL=https://brightbrains.pk/elestore
   ```
   *(Ensure to use `https://` if your site has SSL active, or `http://` if not)*.
3. Save the `.env` file. This forces the `@vite` directive to correctly prepend `/elestore` to all compiled styles and scripts.

### Action items for Subfolder:
1. When uploading the zip to cPanel, make sure you overwrite or include the **root `.htaccess`** with this updated configuration.
2. Ensure your cPanel `.env` configures both `APP_URL` and `ASSET_URL` as shown above.
3. This stops the routing loop and ensures that static files in `public/build/assets` are returned immediately as correct JS and CSS mime-types!

---

## 🔄 Step 6: Verify Endpoint Communication
Once configured, all client-side modules exchange data smoothly via direct API endpoints:
- Fetching operations summary: `http://brightbrains.pk/elestore/api/summary/br-01`
- Catalog items: `http://brightbrains.pk/elestore/api/products`
- Posting diagnostic tickets: `http://brightbrains.pk/elestore/api/repairs`
- Ledger balances check: `http://brightbrains.pk/elestore/api/accounting/trial-balance`

---

## 🕒 Step 7: Adding the Task Scheduler / Cron Job
Laravel requires a single cron job to manage its task schedules (like inventory alerts, report generation, system logging, or cleanups). Here is how to register it in your cPanel dashboard.

### 📋 cPanel Cron Job Configuration Settings

1. Log in to your **cPanel Dashboard**.
2. Search for and open **Cron Jobs** under the **Advanced** section.
3. Scroll down to the **Add New Cron Job** section.
4. Select or enter the following settings:
   - **Common Settings**: `-- Common Settings --` (Choose **Once Per Minute (* * * * *)** from the dropdown menu)
   - **Minute**: `*` (Once per minute)
   - **Hour**: `*` (Every hour)
   - **Day**: `*` (Every day)
   - **Month**: `*` (Every month)
   - **Weekday**: `*` (Every weekday)
   - **Command**: Copy and paste the appropriate command below according to your path and PHP version:

#### 💻 Command Configuration (Option A: Direct Subfolder Upload)
If you uploaded the project directly under `/public_html/elestore`:
```bash
/usr/local/bin/ea-php82 /home/brightbrai/public_html/elestore/artisan schedule:run >> /dev/null 2>&1
```
*Note: If your domain's assigned PHP version is PHP 8.3, replace `ea-php82` with `ea-php83`. If you are using standard PHP, use `/usr/local/bin/php`.*

#### 🔒 Command Configuration (Option B: Root Folder Separation - Secure)
If you placed the core codebase above `public_html` under `/home/brightbrai/laravel-core`:
```bash
/usr/local/bin/ea-php82 /home/brightbrai/laravel-core/artisan schedule:run >> /dev/null 2>&1
```

5. Click **Add New Cron Job** to save.

---
*Maintained under official deployment guidelines for B