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

include __DIR__ . "/includes/config.php";

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

if (!isset($_GET['id']) || empty($_GET['id'])) {
    die("Invalid Product ID");
}
$id = intval($_GET['id']);

// --- FETCH PRODUCT ---
$stmt = $conn->prepare("SELECT * FROM products WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$product = $result->fetch_assoc();
$stmt->close();

if (!$product) {
    die("Product not found!");
}

$updated = false;
$errorMsg = "";

// --- UPDATE PRODUCT ---
if (isset($_POST['update_product'])) {
    $name = $_POST['name'];
    $price = $_POST['price'];
    $daily = $_POST['daily'];
    $days = $_POST['days'];
    $total = $_POST['total'];
    $category = $_POST['category'];
    $status = $_POST['status'];

    $imageName = $product['image']; 
    
    // ✅ FIX: Use Server Root Path for Updates (Consistent with products.php)
    $baseDir = $_SERVER['DOCUMENT_ROOT'];
    $targetDir = $baseDir . "/images/products/";
    
    if (!empty($_FILES['image']['name'])) {
        
        // Ensure directory exists
        if (!file_exists($targetDir)) {
            mkdir($targetDir, 0777, true);
        }
        
        // Secure Rename
        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $newImageName = time() . "_" . uniqid() . "." . $ext;
        $targetFile = $targetDir . $newImageName;
        
        if(move_uploaded_file($_FILES['image']['tmp_name'], $targetFile)){
            // Purani image delete karein agar nayi upload hui hai
            if(!empty($imageName) && file_exists($targetDir . $imageName)){
                unlink($targetDir . $imageName);
            }
            $imageName = $newImageName;
        } else {
             $errorMsg = "Image Upload Failed! Check permissions for path: $targetDir";
        }
    }

    if (empty($errorMsg)) {
        $stmt = $conn->prepare("UPDATE products SET name=?, price=?, daily=?, days=?, total=?, category=?, status=?, image=? WHERE id=?");
        $stmt->bind_param("siiiisssi", $name, $price, $daily, $days, $total, $category, $status, $imageName, $id);
        
        if($stmt->execute()){
            $stmt->close();
            $updated = true;
            // Refresh product data to show updated values immediately
            $stmt = $conn->prepare("SELECT * FROM products WHERE id=?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $product = $stmt->get_result()->fetch_assoc();
            $stmt->close();
        } else {
            $errorMsg = "Database Error: " . $conn->error;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Product</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<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: 800px;
        margin: 30px auto;
        padding: 0 20px;
    }

    /* --- CARD --- */
    .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;
    }
    .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: 15px; }
    .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: 0 5px 15px rgba(40, 167, 69, 0.3);
    }

    .preview-img {
        width: 100px;
        height: 100px;
        object-fit: cover;
        border-radius: 8px;
        margin-top: 10px;
        border: 1px solid var(--border);
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        background: #f8f9fa;
    }
    
    .alert-error {
        background: #f8d7da;
        color: #721c24;
        padding: 12px;
        border-radius: 8px;
        margin-bottom: 20px;
        font-weight: 500;
        border: 1px solid #f5c6cb;
    }
</style>
</head>
<body>

<div class="topbar">
    <div class="topbar-title">
        <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>
        EDIT PRODUCT
    </div>
    <a href="products.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">
    
    <?php if(!empty($errorMsg)): ?>
        <div class="alert-error">
            ⚠️ <?=$errorMsg?>
        </div>
    <?php endif; ?>

    <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="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>
            Update Details (ID: <?=$product['id']?>)
        </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" value="<?=htmlspecialchars($product['name'])?>" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Price (₹)</label>
                        <input type="number" name="price" value="<?=$product['price']?>" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Daily Income (₹)</label>
                        <input type="number" name="daily" value="<?=$product['daily']?>" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Duration (Days)</label>
                        <input type="number" name="days" value="<?=$product['days']?>" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Total Income (₹)</label>
                        <input type="number" name="total" value="<?=$product['total']?>" class="form-control" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Category</label>
                        <select name="category" class="form-control" required>
                            <option value="long" <?=$product['category']=='long'?'selected':''?>>Long-Income</option>
                            <option value="vip" <?=$product['category']=='vip'?'selected':''?>>VIP-Income</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Status</label>
                        <select name="status" class="form-control" required>
                            <option value="active" <?=$product['status']=='active'?'selected':''?>>Active</option>
                            <option value="upcoming" <?=$product['status']=='upcoming'?'selected':''?>>Upcoming</option>
                            <option value="out" <?=$product['status']=='out'?'selected':''?>>Out of Stock</option>
                        </select>
                    </div>

                    <div class="form-group" style="grid-column: 1 / -1;">
                        <label>Product Image (Leave empty to keep current)</label>
                        <input type="file" name="image" class="form-control" accept="image/*" style="padding: 9px;">
                        <?php if(!empty($product['image'])): ?>
                            <div style="margin-top: 10px;">
                                <small style="color: var(--text-light);">Current Image:</small><br>
                                <!-- Using Root Web Path for display -->
                                <img src="/images/products/<?=$product['image']?>" class="preview-img" onerror="this.src='https://via.placeholder.com/100?text=Error'">
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <button type="submit" name="update_product" class="btn-submit">
                    <svg class="svg-icon" viewBox="0 0 24 24"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path><polyline points="17 21 17 13 7 13 7 21"></polyline><polyline points="7 3 7 8 15 8"></polyline></svg>
                    Save Changes
                </button>
            </form>
        </div>
    </div>
</div>

<?php if ($updated): ?>
<script>
Swal.fire({
  icon: 'success',
  title: 'Updated Successfully!',
  text: 'Product details have been saved.',
  confirmButtonColor: '#28a745',
  background: '#fff',
  color: '#333'
}).then(() => {
  window.location.href = "products.php";
});
</script>
<?php endif; ?>

</body>
</html>