# Sub2me Borehole Tech - Management System

A complete borehole drilling project management system with flexible payment tracking, agent management, and financial reporting.

## 🚀 Features

- **Flexible Payment System**: Percentage-based or custom payment amounts
- **Project Management**: Track projects from quote to completion
- **Agent Management**: Monitor agent performance and outstanding balances
- **Financial Reports**: Monthly profit/loss statements with cost breakdowns
- **Payment Tracking**: Record initial payments, balance payments, and view outstanding dues
- **Activity Logging**: Complete audit trail of all project activities
- **User Authentication**: Secure login system with role-based access

## 📋 Requirements

- PHP 7.4 or higher
- MySQL 5.7 or higher
- Web server (Apache/Nginx)
- Modern web browser

## 🔧 Installation Instructions

### Step 1: Upload Files

1. Download and extract the `borehole_system.zip` file
2. Upload all files to your web server (e.g., `public_html/borehole` or `/var/www/html/borehole`)

### Step 2: Create Database

1. Log in to your cPanel or phpMyAdmin
2. Create a new database (e.g., `borehole_tech`)
3. Create a database user and grant all privileges
4. Import the `install.sql` file into your new database

**In phpMyAdmin:**
- Select your database
- Click "Import" tab
- Choose `install.sql` file
- Click "Go"

**Via MySQL command line:**
```bash
mysql -u your_username -p borehole_tech < install.sql
```

### Step 3: Configure Database Connection

1. Open `config.php` in a text editor
2. Update these lines with your database details:

```php
define('DB_HOST', 'localhost');        // Usually 'localhost'
define('DB_USERNAME', 'your_username'); // Your database username
define('DB_PASSWORD', 'your_password'); // Your database password
define('DB_NAME', 'borehole_tech');    // Your database name
```

3. Update the site URL:
```php
define('SITE_URL', 'https://yourdomain.com/borehole_system');
```

4. Save the file

### Step 4: Set File Permissions (if on Linux/Unix)

```bash
chmod 755 /path/to/borehole_system
chmod 644 /path/to/borehole_system/*.php
```

### Step 5: Access the System

1. Open your browser and go to: `https://yourdomain.com/borehole_system/`
2. You will be redirected to the login page

**Default Login Credentials:**
- Username: `admin`
- Password: `admin123`

**⚠️ IMPORTANT: Change the admin password immediately after first login!**

## 📊 Default Settings

The system comes pre-configured with:

- Default rate per meter: ₦12,500
- Initial payment percentage: 70%
- Diesel price: ₦990/liter
- GM commission: ₦500/meter
- CEO commission: ₦1,500/meter
- Staff daily feeding: ₦2,500
- Number of site workers: 6
- Monthly target: 20 boreholes

You can adjust these in the settings table in your database.

## 📱 Quick Start Guide

### Creating Your First Project

1. **Login** with admin credentials
2. Click **"+ New Project"** in the navigation
3. Fill in project details:
   - Select agent (or add new agent first)
   - Enter location
   - Set depth required (default: 70m)
   - Choose payment terms:
     - **Standard**: Use percentage split (70/30, 50/50, etc.)
     - **Custom**: Enter any manual amount
   - Add discounts or additional charges if needed
4. Click **"Save Project"**

### Recording Payments

1. Go to project details page
2. Click **"Record Initial Payment"** or **"Record Balance Payment"**
3. Enter payment details:
   - Amount (pre-filled with expected amount)
   - Payment method (Cash, Transfer, POS, etc.)
   - Payment reference/transaction ID
   - Payment date
4. Click **"Record Payment"**

### Managing Agents

1. Go to **"Agents"** in navigation
2. Click **"+ Add New Agent"**
3. Enter agent details (name, phone, WhatsApp, etc.)
4. View agent performance metrics:
   - Total projects
   - Total revenue generated
   - Outstanding balances
   - Performance rating

### Viewing Reports

1. Go to **"Reports"** in navigation
2. Select month to view
3. See comprehensive breakdown:
   - Revenue vs Target
   - Cost analysis
   - Net profit and margins
   - List of completed projects

## 🔐 Security Notes

1. **Change Default Password**: Immediately change the admin password after installation
2. **Database Backups**: Regularly backup your database
3. **SSL Certificate**: Use HTTPS for secure data transmission
4. **File Permissions**: Ensure proper file permissions are set

## 🛠️ Troubleshooting

### Cannot Connect to Database

**Error**: "Database Connection Failed"

**Solution**:
- Check `config.php` has correct database credentials
- Verify database exists
- Ensure database user has proper privileges
- Test database connection separately

### Blank Page After Login

**Solution**:
- Check PHP error logs
- Ensure all files were uploaded correctly
- Verify database tables were created (check install.sql imported successfully)

### Session Errors

**Solution**:
- Ensure your server has session support enabled
- Check folder permissions for session storage

## 📞 Support

For issues or questions:
- Check the database structure in `install.sql`
- Review PHP error logs
- Verify all configuration in `config.php`

## 🔄 Database Backup

**Recommended**: Backup your database weekly

**Via phpMyAdmin**:
1. Select your database
2. Click "Export"
3. Choose "Quick" or "Custom" method
4. Click "Go"
5. Save the .sql file

**Via Command Line**:
```bash
mysqldump -u your_username -p borehole_tech > backup_$(date +%Y%m%d).sql
```

## 📄 File Structure

```
borehole_system/
├── config.php              # Database configuration
├── install.sql             # Database installation script
├── login.php               # Login page
├── logout.php              # Logout handler
├── header.php              # Page header template
├── footer.php              # Page footer template
├── index.php               # Dashboard
├── add_project.php         # Create new project
├── save_project.php        # Save project handler
├── projects.php            # List all projects
├── project_details.php     # View project details
├── edit_project.php        # Edit project
├── update_status.php       # Update project status
├── record_payment.php      # Record payments
├── payments.php            # Payments overview
├── agents.php              # Agent management
├── reports.php             # Financial reports
└── README.txt              # This file
```

## ⚙️ Advanced Configuration

### Adding More Users

Run this SQL to add users:
```sql
INSERT INTO users (username, password, full_name, role) 
VALUES ('john', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'John Doe', 'manager');
```

Note: Password is hashed. Use online bcrypt generator or PHP's `password_hash()` function.

### Modifying Default Settings

Update settings in database:
```sql
UPDATE settings SET setting_value = '15000' WHERE setting_key = 'default_rate_per_meter';
```

## 📈 Usage Tips

1. **Regular Backups**: Backup database weekly
2. **Monitor Outstanding**: Check payments page daily for overdue balances
3. **Agent Performance**: Review agent stats monthly
4. **Monthly Reports**: Generate and save monthly reports for records
5. **Activity Logs**: Use project activity logs to track changes

## 🎯 System Workflow

1. Agent brings a job → Create new project
2. Record initial payment (70% or custom) → Status: Approved
3. Assign team and start drilling → Status: In Progress
4. Complete drilling → Update status: Completed (with depth achieved)
5. Collect balance payment → Status: Fully Paid
6. Generate monthly reports → Track profitability

## 📝 Version

Version: 1.0
Created: January 2026
Created for: Sub2me Borehole Tech

---

**Developed specifically for borehole drilling business management with flexible payment tracking and comprehensive financial reporting.**
