<?php
session_start();
include 'includes/header.php';
include 'includes/sidebar.php';
include 'includes/connect.php';

// Upload folder
$upload_dir = "uploads/aadhar/";
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Get distributor ID
if(!isset($_GET['id']) || empty($_GET['id'])){
    echo "<script>alert('Invalid Distributor ID'); window.location.href='distributor_list.php';</script>";
    exit;
}
$id = intval($_GET['id']);

// Fetch distributor data
$query = "SELECT * FROM distributor WHERE id = $id";
$result = mysqli_query($conn, $query);

if(mysqli_num_rows($result) == 0){
    echo "<script>alert('Distributor not found'); window.location.href='distributor_list.php';</script>";
    exit;
}

$distributor = mysqli_fetch_assoc($result);

// Handle update
if(isset($_POST['update_distributor'])){
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
    $address = mysqli_real_escape_string($conn, $_POST['address']);
    $password_raw = $_POST['password'];
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    $aadhar_number = mysqli_real_escape_string($conn, $_POST['aadhar_number']);

    // Password hash
    $password = password_hash($password_raw, PASSWORD_DEFAULT);

    // File upload
    $file_name = $_FILES['aadhar_file']['name'];
    $file_tmp  = $_FILES['aadhar_file']['tmp_name'];
    $file_size = $_FILES['aadhar_file']['size'];
    $file_error= $_FILES['aadhar_file']['error'];

    // Validation
    if(empty($name) || empty($email) || empty($mobile) || empty($address) || empty($password_raw) || empty($aadhar_number)){
        $error = "All fields are required.";
    } elseif(!preg_match('/^[0-9]{10,15}$/', $mobile)){
        $error = "Mobile must be numeric (10-15 digits).";
    } elseif(!preg_match('/^[0-9]{12}$/', $aadhar_number)){
        $error = "Aadhar must be 12 digits.";
    } else {

        // Default: keep old file
        $new_file_name = $distributor['aadhar_file'];

        // If new file uploaded
        if(!empty($file_name)){

            $allowed_ext = ['jpg','jpeg','png','pdf'];
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

            if(!in_array($file_ext, $allowed_ext)){
                $error = "Only JPG, PNG, PDF allowed";
            } elseif($file_size > 2*1024*1024){
                $error = "File must be less than 2MB";
            } else {

                $new_file_name = time() . "_" . rand(1000,9999) . "." . $file_ext;
                $final_path = $upload_dir . $new_file_name;

                if(move_uploaded_file($file_tmp, $final_path)){
                    
                    // delete old file
                    if(!empty($distributor['aadhar_file']) && file_exists($upload_dir.$distributor['aadhar_file'])){
                        unlink($upload_dir.$distributor['aadhar_file']);
                    }

                } else {
                    $error = "File upload failed";
                }
            }
        }

        if(!isset($error)){
            $update = "UPDATE distributor SET 
                        name='$name',
                        email='$email',
                        mobile='$mobile',
                        address='$address',
                        password='$password',
                        status='$status',
                        aadhar_number='$aadhar_number',
                        aadhar_file='$new_file_name'
                       WHERE id=$id";

            if(mysqli_query($conn, $update)){
                echo "<script>alert('Distributor updated successfully'); window.location.href='distributor_list.php';</script>";
                exit;
            } else {
                $error = "Error updating distributor.";
            }
        }
    }
}
?>

<div class="main-content-inner">
    <div class="main-content-wrap">

        <div class="flex items-center flex-wrap justify-between gap20 mb-30">
            <h3>Edit Distributor</h3>
        </div>

        <div class="wg-box">

            <?php if(isset($error)){ ?>
                <div class="text-red-500 mb-4"><?php echo $error; ?></div>
            <?php } ?>

            <form method="POST" enctype="multipart/form-data">

                <div class="wg-box mb-30">
                    <div style="display:flex; flex-wrap:wrap; gap:20px;">

                        <fieldset style="flex:1; min-width:200px;">
                            <div class="body-title mb-10">Distributor Name *</div>
                            <input type="text" name="name" value="<?php echo htmlspecialchars($distributor['name']); ?>" required>
                        </fieldset>

                        <fieldset style="flex:1; min-width:200px;">
                            <div class="body-title mb-10">Email *</div>
                            <input type="email" name="email" value="<?php echo htmlspecialchars($distributor['email']); ?>" required>
                        </fieldset>

                        <fieldset style="flex:1; min-width:200px;">
                            <div class="body-title mb-10">Mobile No *</div>
                            <input type="text" name="mobile" value="<?php echo htmlspecialchars($distributor['mobile']); ?>" required>
                        </fieldset>

                        <fieldset style="flex:1; min-width:200px;">
                            <div class="body-title mb-10">Address *</div>
                            <input type="text" name="address" value="<?php echo htmlspecialchars($distributor['address']); ?>" required>
                        </fieldset>

                        <fieldset style="flex:1; min-width:200px;">
                            <div class="body-title mb-10">Password *</div>
                            <input type="text" name="password" placeholder="Enter new password" required>
                        </fieldset>

                        <fieldset style="flex:1; min-width:150px;">
                            <div class="body-title mb-10">Status *</div>
                            <select name="status" required>
                                <option value="Active" <?php if($distributor['status']=="Active") echo 'selected'; ?>>Active</option>
                                <option value="Inactive" <?php if($distributor['status']=="Inactive") echo 'selected'; ?>>Inactive</option>
                            </select>
                        </fieldset>

                        <!-- Aadhar Number -->
                        <fieldset style="flex:1; min-width:200px;">
                            <div class="body-title mb-10">Aadhar Number *</div>
                            <input type="text" name="aadhar_number" value="<?php echo htmlspecialchars($distributor['aadhar_number']); ?>" required>
                        </fieldset>

                        <!-- Aadhar File -->
                        <fieldset style="flex:1; min-width:200px;">
                            <div class="body-title mb-10">Upload New Aadhar</div>
                            <input type="file" name="aadhar_file" accept=".jpg,.jpeg,.png,.pdf">
                            
                            <?php if(!empty($distributor['aadhar_file'])){ ?>
                                <br><br>
                                <a href="uploads/aadhar/<?php echo $distributor['aadhar_file']; ?>" target="_blank" class="tf-button style-3">View Current</a>
                            <?php } ?>
                        </fieldset>

                    </div>
                </div>

                <div class="cols gap10">
                    <button type="submit" name="update_distributor" class="tf-button w380">Update Distributor</button>
                    <a href="distributor_list.php" class="tf-button style-3 w380">Cancel</a>
                </div>

            </form>
        </div>

    </div>
</div>

<?php include 'includes/footer.php'; ?>