<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();

// Config path check kar lena
include __DIR__ . "/includes/config.php";

if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit();
}

// --- HANDLE FORM SUBMISSION ---
if (isset($_POST['add_product'])) {
    $name = $_POST['name'];
    $price = $_POST['price'];
    $daily = $_POST['daily'];
    $days = $_POST['days'];
    $total = $_POST['total'];
    $category = $_POST['category'];
    $status = $_POST['status'];

    $imageName = "";
    
    // ✅ STEP 1: Define Path
    // __DIR__ use kar rahe hain taaki exact location mile
    $targetDir = __DIR__ . "/images/products/";
    
    if (!empty($_FILES['image']['name'])) {
        
        // ✅ STEP 2: Check Upload Errors from PHP
        if ($_FILES['image']['error'] !== UPLOAD_ERR_OK) {
            $phpErrorCode = $_FILES['image']['error'];
            die("<h3>Upload Failed!</h3> PHP Error Code: <b>$phpErrorCode</b>.<br> (Code 2 means file too big, Code 6/7 means temp folder missing).");
        }

        // ✅ STEP 3: Create Folder if missing
        if (!file_exists($targetDir)) {
            if (!mkdir($targetDir, 0777, true)) {
                die("<h3>Error:</h3> Folder nahi bana paaye. <br>Path: $targetDir <br>Please create 'images/products' manually in File Manager.");
            }
        }
        
        // ✅ STEP 4: Check Write Permission
        if (!is_writable($targetDir)) {
            // Try to fix permission automatically
            @chmod($targetDir, 0777);
            
            // Check again
            if (!is_writable($targetDir)) {
                 die("<h3>Permission Denied!</h3> Server is not allowing to write in this folder.<br><b>Path:</b> $targetDir <br><b>Solution:</b> Go to cPanel/File Manager > Right Click on 'products' folder > Change Permissions to <b>777</b>.");
            }
        }
        
        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $imageName = time() . "_" . uniqid() . "." . $ext;
        $targetFile = $targetDir . $imageName;
        
        // ✅ STEP 5: Move File
        if (move_uploaded_file($_FILES['image']['tmp_name'], $targetFile)) {
            // Success
        } else {
            die("<h3>Critical Error:</h3> File move nahi ho paayi even though folder writable lag raha hai.<br>Target: $targetFile"); 
        }
    }

    // Database Insert
    $stmt = $conn->prepare("INSERT INTO products (name, price, daily, days, total, category, status, image) VALUES (?,?,?,?,?,?,?,?)");
    $stmt->bind_param("siiiisss", $name, $price, $daily, $days, $total, $category, $status, $imageName);
    
    if($stmt->execute()){
        $stmt->close();
        header("Location: products.php");
        exit();
    } else {
        echo "Database Error: " . $stmt->error;
    }
}

// --- HANDLE DELETE ---
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    
    $q = $conn->query("SELECT image FROM products WHERE id=$id");
    if($r = $q->fetch_assoc()){
        $path = __DIR__ . "/images/products/" . $r['image'];
        if(file_exists($path) && !empty($r['image'])) {
            unlink($path);
        }
    }

    $conn->query("DELETE FROM products WHERE id=$id");
    header("Location: products.php");
    exit();
}

$products = $conn->query("SELECT * FROM products ORDER BY id DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Manage Products</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
    /* --- RESET & VARS --- */
    :root {
        --primary: #0047ab;
        --primary-dark: #003380;
        --accent: #1a73e8;
        --bg: #f0f4fb;
        --surface: #ffffff;
        --text: #333333;
        --text-light: #666666;
        --border: #dbe6f6;
    }
    
    body {
        font-family: 'Segoe UI', system-ui, sans-serif;
        background: linear-gradient(135deg, #f0f4fb, #dbe6f6);
        color: var(--text);
        margin: 0;
        padding-bottom: 40px;
    }

    /* --- ICONS --- */
    .svg-icon {
        width: 18px;
        height: 18px;
        vertical-align: middle;
        fill: none;
        stroke: currentColor;
        stroke-width: 2;
        stroke-linecap: round;
        stroke-linejoin: round;
    }

    /* --- TOPBAR --- */
    .topbar {
        background: linear-gradient(90deg, var(--primary), var(--accent));
        color: #fff;
        padding: 16px 24px;
        font-weight: 700;
        font-size: 18px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-shadow: 0 4px 20px rgba(0,0,0,0.15);
        position: sticky;
        top: 0;
        z-index: 100;
    }
    .topbar-title { display: flex; align-items: center; gap: 10px; }
    
    .back-btn {
        background: rgba(255,255,255,0.2);
        color: #fff;
        padding: 8px 16px;
        border-radius: 8px;
        text-decoration: none;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 6px;
        transition: 0.3s;
    }
    .back-btn:hover { background: rgba(255,255,255,0.3); }

    /* --- CONTAINER --- */
    .container {
        max-width: 1200px;
        margin: 30px auto;
        padding: 0 20px;
    }

    /* --- CARDS --- */
    .card {
        background: var(--surface);
        border-radius: 16px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.05);
        border: 1px solid rgba(255,255,255,0.5);
        overflow: hidden;
        margin-bottom: 30px;
    }
    .card-header {
        padding: 20px 24px;
        border-bottom: 1px solid var(--border);
        background: rgba(240, 244, 251, 0.5);
        font-size: 18px;
        font-weight: 700;
        color: var(--primary);
        display: flex;
        align-items: center;
        gap: 10px;
    }

    /* --- FORM --- */
    .form-content { padding: 24px; }
    .form-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 20px;
    }
    .form-group { margin-bottom: 5px; }
    .form-group label {
        display: block;
        margin-bottom: 8px;
        font-size: 14px;
        font-weight: 600;
        color: var(--text-light);
    }
    .form-control {
        width: 100%;
        padding: 12px 16px;
        border: 1px solid #d1d9e6;
        border-radius: 10px;
        font-size: 14px;
        background: #fdfdfd;
        transition: 0.3s;
        box-sizing: border-box; 
    }
    .form-control:focus {
        border-color: var(--accent);
        outline: none;
        box-shadow: 0 0 0 3px rgba(26, 115, 232, 0.1);
    }
    
    .btn-submit {
        background: linear-gradient(90deg, #28a745, #3ecf5e);
        color: white;
        border: none;
        padding: 14px;
        border-radius: 10px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        width: 100%;
        margin-top: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 8px;
        transition: transform 0.2s, box-shadow 0.2s;
    }
    .btn-submit:hover {
        transform: translateY(-2px);
        box-shadow: 5px 15px rgba(40, 167, 69, 0.3);
    }

    /* --- TABLE --- */
    .table-responsive { overflow-x: auto; }
    table {
        width: 100%;
        border-collapse: collapse;
        font-size: 14px;
    }
    th {
        background: #f8f9fa;
        color: var(--text-light);
        font-weight: 600;
        text-transform: uppercase;
        font-size: 12px;
        letter-spacing: 0.5px;
        padding: 16px;
        text-align: left;
        border-bottom: 2px solid var(--border);
    }
    td {
        padding: 16px;
        border-bottom: 1px solid var(--border);
        vertical-align: middle;
    }
    tr:last-child td { border-bottom: none; }
    tr:hover { background-color: #fcfcfc; }

    .product-img {
        width: 50px;
        height: 50px;
        border-radius: 8px;
        object-fit: cover;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        border: 1px solid var(--border);
        background: #eee;
    }

    /* --- BADGES --- */
    .badge {
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 700;
        display: inline-flex;
        align-items: center;
        gap: 4px;
    }
    .badge-active { background: #d4edda; color: #155724; }
    .badge-upcoming { background: #fff3cd; color: #856404; }
    .badge-out { background: #f8d7da; color: #721c24; }

    /* --- ACTIONS --- */
    .action-btn {
        padding: 8px;
        border-radius: 8px;
        display: inline-flex;
        text-decoration: none;
        transition: 0.2s;
        margin-right: 4px;
    }
    .btn-edit { background: #e2e6ea; color: var(--primary); }
    .btn-edit:hover { background: #dbe2ef; color: var(--primary-dark); }
    
    .btn-delete { background: #f8d7da; color: var(--danger); }
    .btn-delete:hover { background: #f5c6cb; color: #a71d2a; }

    @media (max-width: 768px) {
        .form-grid { grid-template-columns: 1fr; }
    }
</style>
</head>
<body>

<div class="topbar">
    <div class="topbar-title">
        <svg class="svg-icon" viewBox="0 0 24 24" style="width:24px;height:24px;"><path d="M20 7h-9c-1.1 0-2 .9-2 2v9c0 1.1.9 2 2 2h9c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zM4 11h6M4 15h6M4 7h6"/></svg>
        COSCO ADMIN
    </div>
    <a href="dashboard.php" class="back-btn">
        <svg class="svg-icon" viewBox="0 0 24 24"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
        Back
    </a>
</div>

<div class="container">

    <div class="card">
        <div class="card-header">
            <svg class="svg-icon" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="16"></line><line x1="8" y1="12" x2="16" y2="12"></line></svg>
            Add New Product
        </div>
        <div class="form-content">
            <form method="POST" enctype="multipart/form-data">
                <div class="form-grid">
                    <div class="form-group">
                        <label>Product Name</label>
                        <input type="text" name="name" class="form-control" placeholder="e.g. Gold Plan" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Price (₹)</label>
                        <input type="number" name="price" class="form-control" placeholder="0.00" required>
                    </div>

                    <div class="form-group">
                        <label>Daily Income (₹)</label>
                        <input type="number" name="daily" class="form-control" placeholder="0.00" required>
                    </div>

                    <div class="form-group">
                        <label>Duration (Days)</label>
                        <input type="number" name="days" class="form-control" placeholder="30" required>
                    </div>

                    <div class="form-group">
                        <label>Total Income (₹)</label>
                        <input type="number" name="total" class="form-control" placeholder="0.00" required>
                    </div>

                    <div class="form-group">
                        <label>Category</label>
                        <select name="category" class="form-control" required>
                            <option value="long">Long-Income</option>
                            <option value="vip">VIP-Income</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Status</label>
                        <select name="status" class="form-control" required>
                            <option value="active">Active</option>
                            <option value="upcoming">Upcoming</option>
                            <option value="out">Out of Stock</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Product Image</label>
                        <input type="file" name="image" accept="image/*" class="form-control" style="padding: 9px;" required>
                    </div>
                </div>

                <button type="submit" name="add_product" class="btn-submit">
                    <svg class="svg-icon" viewBox="0 0 24 24"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
                    Create Product
                </button>
            </form>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <svg class="svg-icon" viewBox="0 0 24 24"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path><polyline points="3.27 6.96 12 12.01 20.73 6.96"></polyline><line x1="12" y1="22.08" x2="12" y2="12"></line></svg>
            All Products
        </div>
        <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th width="50">ID</th>
                        <th width="70">Image</th>
                        <th>Name</th>
                        <th>Price</th>
                        <th>Daily</th>
                        <th>Days</th>
                        <th>Total</th>
                        <th>Type</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while($p = $products->fetch_assoc()): ?>
                    <tr>
                        <td>#<?=$p['id']?></td>
                        <td>
                            <img src="images/products/<?=$p['image']?>" class="product-img" alt="Prod" onerror="this.onerror=null;this.src='https://via.placeholder.com/50?text=Err';">
                        </td>
                        <td><strong><?=htmlspecialchars($p['name'])?></strong></td>
                        <td>₹<?=number_format($p['price'])?></td>
                        <td>₹<?=number_format($p['daily'])?></td>
                        <td><?=$p['days']?>d</td>
                        <td>₹<?=number_format($p['total'])?></td>
                        <td style="text-transform: capitalize; color:var(--text-light);"><?=htmlspecialchars($p['category'])?></td>
                        <td>
                            <?php if($p['status']=='active'): ?>
                                <span class="badge badge-active">
                                    <svg class="svg-icon" style="width:12px;height:12px;" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg> Active
                                </span>
                            <?php elseif($p['status']=='upcoming'): ?>
                                <span class="badge badge-upcoming">
                                    <svg class="svg-icon" style="width:12px;height:12px;" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg> Upcoming
                                </span>
                            <?php else: ?>
                                <span class="badge badge-out">
                                    <svg class="svg-icon" style="width:12px;height:12px;" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"></circle><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"></line></svg> Out
                                </span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <a href="edit_product.php?id=<?=$p['id']?>" class="action-btn btn-edit" title="Edit">
                                <svg class="svg-icon" viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>
                            </a>
                            <a href="products.php?delete=<?=$p['id']?>" onclick="return confirm('Are you sure you want to delete this product?')" class="action-btn btn-delete" title="Delete">
                                <svg class="svg-icon" viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>
                            </a>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>

</div>
</body>
</html>