<?php
// install_db.php - RUN THIS ONCE TO FIX "LOADING" ERRORS
require 'db.php';

echo "<h1>🛠️ System Database Installer</h1>";

try {
    // 1. Create Stock List Table
    $pdo->exec("CREATE TABLE IF NOT EXISTS stock_list (
        id INT AUTO_INCREMENT PRIMARY KEY,
        type VARCHAR(50) DEFAULT 'Part', -- Part or Retail
        model_group VARCHAR(100),        -- e.g. iPhone 13
        device_model VARCHAR(100),       -- e.g. Pro Max
        part_name VARCHAR(100),          -- e.g. LCD Screen
        cost DECIMAL(10,2) DEFAULT 0,
        supplier VARCHAR(100),
        stock_gombak INT DEFAULT 0,
        stock_sr INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    echo "✅ Table 'stock_list' created/checked.<br>";

    // 2. Create Stock Transfers Table (For logs)
    $pdo->exec("CREATE TABLE IF NOT EXISTS stock_transfers (
        id INT AUTO_INCREMENT PRIMARY KEY,
        item_name VARCHAR(100),
        qty INT,
        from_branch VARCHAR(50),
        to_branch VARCHAR(50),
        user VARCHAR(50),
        date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    echo "✅ Table 'stock_transfers' created/checked.<br>";

    // 3. Create Jobs Table (Just in case)
    $pdo->exec("CREATE TABLE IF NOT EXISTS jobs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        job_id VARCHAR(20) UNIQUE,
        branch VARCHAR(50),
        date DATE,
        customer VARCHAR(100),
        phone VARCHAR(50),
        model VARCHAR(100),
        imei VARCHAR(100),
        passcode VARCHAR(100),
        repair TEXT,
        price DECIMAL(10,2),
        status VARCHAR(50),
        remarks TEXT,
        pickup_date DATE,
        warranty VARCHAR(50),
        payment_method VARCHAR(50),
        token VARCHAR(100),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    echo "✅ Table 'jobs' created/checked.<br>";

    // 4. Create Customers Table
    $pdo->exec("CREATE TABLE IF NOT EXISTS customers (
        id INT AUTO_INCREMENT PRIMARY KEY,
        phone VARCHAR(50) UNIQUE,
        name VARCHAR(100),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    echo "✅ Table 'customers' created/checked.<br>";

    echo "<h3>🎉 All tables are ready! You can delete this file now.</h3>";
    echo "<a href='dashboard.php'>Go back to Dashboard</a>";

} catch (PDOException $e) {
    echo "<h2>❌ Error: " . $e->getMessage() . "</h2>";
}
?>