# KiyoKart - Lightweight E-commerce Application

A performance-optimized e-commerce application built with Laravel 11, featuring server-side rendering with Blade templates, Bootstrap 5, OTP-based authentication, Razorpay payments, and Delhivery shipping integration.

## 🚀 Features

### Customer Features
- **OTP-based Authentication** - Passwordless login for customers using Fast2SMS
- **Product Browsing** - Categories, featured products, search functionality
- **Shopping Cart** - Add/update/remove items with real-time total calculation
- **Coupon System** - Apply discount coupons (percentage or flat)
- **Checkout & Payment** - Secure payment via Razorpay integration
- **Order Tracking** - View order history and track shipments
- **Profile Management** - Manage addresses and personal information

### Admin Features
- **Dashboard** - Revenue charts, order statistics, recent orders
- **Product Management** - CRUD operations with image upload
- **Category Management** - Hierarchical category structure
- **Order Management** - View, update order status, process refunds
- **Shipping Integration** - Generate Delhivery AWB and labels
- **Coupon Management** - Create and manage discount coupons
- **User Management** - Role-based access control (RBAC)
- **Reports** - Sales reports, top products, payment summary

## 🛠 Tech Stack

- **Framework**: Laravel 11
- **PHP**: 8.2+
- **Frontend**: Blade Templates + Bootstrap 5
- **Database**: MySQL
- **Authentication**: Custom OTP (Fast2SMS)
- **Payment Gateway**: Razorpay
- **Shipping**: Delhivery API
- **Permissions**: Spatie Laravel Permission

## 📦 Key Dependencies

```json
{
  "guzzlehttp/guzzle": "^7.8",
  "razorpay/razorpay": "^2.9",
  "spatie/laravel-permission": "^6.0"
}
```

## 🔧 Installation

### Prerequisites
- PHP 8.2 or higher
- Composer
- MySQL 5.7+ or MariaDB 10.3+
- Node.js & NPM (for asset compilation, optional)

### Step 1: Clone the Repository
```bash
git clone <repository-url>
cd kiyokart
```

### Step 2: Install Dependencies
```bash
composer install
```

### Step 3: Environment Configuration
```bash
cp .env.example .env
php artisan key:generate
```

Edit `.env` file and configure:
- Database credentials
- Razorpay keys (RZP_KEY, RZP_SECRET)
- Fast2SMS API key
- Delhivery API credentials

### Step 4: Database Setup
```bash
php artisan migrate
php artisan db:seed
```

This will create:
- Database tables
- Roles & permissions
- Admin user (mobile: 9999999999, password: password)

### Step 5: Storage Link
```bash
php artisan storage:link
```

### Step 6: Start Development Server
```bash
php artisan serve
```

Visit `http://localhost:8000`

## 🔑 Default Admin Credentials

- **Mobile**: 9999999999
- **Password**: password

**⚠️ IMPORTANT**: Change the admin password immediately in production:

```bash
php artisan tinker
```

```php
User::where('mobile', '9999999999')->first()->update([
    'password' => Hash::make('your-secure-password')
]);
```

## 📁 Project Structure

```
kiyokart/
├── app/
│   ├── Http/
│   │   ├── Controllers/
│   │   │   ├── Admin/          # Admin controllers
│   │   │   ├── Auth/           # Authentication
│   │   │   └── Customer/       # Customer controllers
│   │   ├── Requests/           # Form request validators
│   │   └── Middleware/         # Custom middleware
│   ├── Models/                 # Eloquent models
│   ├── Services/               # Business logic services
│   └── Rules/                  # Custom validation rules
├── database/
│   ├── migrations/             # Database migrations
│   └── seeders/                # Database seeders
├── resources/
│   └── views/
│       ├── layouts/            # Base layouts
│       ├── admin/              # Admin views
│       ├── customer/           # Customer views
│       └── auth/               # Auth views
├── routes/
│   └── web.php                 # Application routes
└── config/
    └── services.php            # 3rd party service configs
```

## 🎯 Common Artisan Commands

### Development
```bash
# Run migrations
php artisan migrate

# Seed database
php artisan db:seed

# Create storage symlink
php artisan storage:link

# Clear caches
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
```

### Production Optimization
```bash
# Cache configuration
php artisan config:cache

# Cache routes
php artisan route:cache

# Cache views
php artisan view:cache

# Optimize autoloader
composer dump-autoload --optimize
```

### Create Admin User Manually
```bash
php artisan tinker
```
```php
$user = User::create([
    'name' => 'Admin Name',
    'mobile' => '9876543210',
    'email' => 'admin@example.com',
    'password' => Hash::make('secure-password')
]);
$user->assignRole('admin');
```

## 🔐 Roles & Permissions

### Roles
- **admin** - Full access to all features
- **staff** - Limited access (products, orders)
- **customer** - Frontend access only

### Key Permissions
- `products.*` - Product management
- `orders.*` - Order management
- `coupons.*` - Coupon management
- `users.manage` - User management
- `reports.view` - View reports

## 🌐 Environment Variables

### Application
```env
APP_NAME=KiyoKart
APP_URL=http://localhost
```

### Database
```env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=kiyokart
DB_USERNAME=root
DB_PASSWORD=
```

### Razorpay
```env
RZP_KEY=your_razorpay_key
RZP_SECRET=your_razorpay_secret
```

### Fast2SMS
```env
FAST2SMS_API_KEY=your_fast2sms_key
FAST2SMS_SENDER=KIYO
FAST2SMS_ROUTE=q
FAST2SMS_ENTITY_ID=
FAST2SMS_TEMPLATE_ID_LOGIN=
```

### Delhivery
```env
DELHIVERY_API_URL=https://track.delhivery.com
DELHIVERY_API_TOKEN=your_delhivery_token
DELHIVERY_WAREHOUSE_PIN=500001
DELHIVERY_PICKUP_NAME=KiyoKart
DELHIVERY_PHONE=9000000000
DELHIVERY_ADDRESS_LINE1=Plot 1, Hyderabad
DELHIVERY_CITY=Hyderabad
DELHIVERY_STATE=TS
DELHIVERY_PIN=500001
```

## 📊 Database Schema

### Key Tables
- **users** - User accounts (customers, admin, staff)
- **addresses** - Customer delivery addresses
- **categories** - Product categories (hierarchical)
- **products** - Product catalog
- **carts** - Shopping carts
- **cart_items** - Cart line items
- **orders** - Customer orders
- **order_items** - Order line items
- **coupons** - Discount coupons
- **coupon_redemptions** - Coupon usage tracking
- **otp_codes** - OTP verification codes

## 🔄 Order Status Flow

```
PLACED → CONFIRMED → PACKED → SHIPPED → DELIVERED
                              ↓
                          CANCELLED
```

## 💳 Payment Flow

1. Customer adds items to cart
2. Applies coupon (optional)
3. Proceeds to checkout
4. Selects/adds delivery address
5. Razorpay order created
6. Customer completes payment
7. Payment verification via signature
8. Order created, inventory decremented
9. Coupon redemption recorded
10. Cart cleared

## 📦 Shipping Flow

1. Admin confirms order
2. Generates Delhivery shipment (AWB)
3. Downloads shipping label
4. Updates order status to SHIPPED
5. Customer can track via AWB

## 🚀 Performance Optimizations

- Route caching (`php artisan route:cache`)
- Config caching (`php artisan config:cache`)
- View caching (`php artisan view:cache`)
- Eager loading relationships
- Database indexing on foreign keys, slugs, SKUs
- Pagination for all listings
- Lazy loading images
- Bootstrap 5 via CDN (minimal JS)
- Cache homepage for 10 minutes

## 🧪 Testing

```bash
# Run tests
php artisan test

# With coverage
php artisan test --coverage
```

## 🛡 Security Features

- CSRF protection enabled
- Razorpay signature verification
- OTP expiry (5 minutes)
- Input sanitization
- Role-based access control
- Stock validation (prevent overselling)
- Secure password hashing (bcrypt)

## 📱 Mobile-First Design

- Responsive Bootstrap 5 layouts
- Touch-friendly UI elements
- Mobile-optimized checkout
- Lazy-loaded images

## 🐛 Troubleshooting

### Issue: OTP not sending
- Check Fast2SMS API key and credits
- Verify mobile number format (Indian: 10 digits)
- Check application logs: `storage/logs/laravel.log`

### Issue: Payment verification fails
- Verify Razorpay key and secret
- Check signature verification in logs
- Ensure webhook URL is correct

### Issue: Images not displaying
- Run `php artisan storage:link`
- Check file permissions on `storage/` directory
- Verify `APP_URL` in `.env`

### Issue: Permission denied errors
```bash
chmod -R 775 storage bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache
```

## 📝 License

This project is open-sourced software licensed under the MIT license.

## 👨‍💻 Support

For issues and feature requests, please create an issue in the repository.

## 🙏 Acknowledgments

- Laravel Framework
- Bootstrap 5
- Razorpay
- Fast2SMS
- Delhivery
- Spatie Laravel Permission

---

Built with ❤️ using Laravel 11
